2321e21 发表于 2015-7-9 08:20:38

python compile、eval、exec内建函数


[*]compile函数

    compile()函数允许程序员在运行时刻迅速生成代码对象,然后就可以用exec 语句或者内建函
数eval()来执行这些对象或者对它们进行求值。一个很重要的观点是:exec 和eval()都可以执行字符串格式的Python 代码。当执行字符串形式的代码时,每次都必须对这些代码进行字节编译处理。compile()函数提供了一次性字节代码预编译,以后每次调用的时候,都不用编译了。    compile(source, filename, mode[, flags[, dont_inherit]])   
    第一参数代表了要编译的python 代码。第二个字符串,虽然是必需的,但通常被置为空串。mode参数是个字符串,它用来表明代码对象的类型。有三个可能值:
    'eval' 可求值的表达式[和eval()一起使用]
    'single' 单一可执行语句[和exec或eval()一起使用]
    'exec' 可执行语句组[和exec一起使用]
可求值表达式

1
2
3
>>> eval_code = compile('100 + 200', '', 'eval')
>>> eval(eval_code)
300




单一可执行语句

1
2
3
4
5
6
7
>>> single_code = compile('print "Hello world!"', '', 'single')
>>> single_code
<code object <module> at 0xb76ebd10, file "", line 1>
>>> exec single_code
Hello world!
>>> eval(eval_code)
Hello world!




可执行语句组

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> exec_code = compile("""
... req = input('Count how many numbers? ')
... for eachNum in range(req):
... print eachNum
... """, '', 'exec')
>>> exec exec_code
Count how many numbers? 6
0
1
2
3
4
5





2.eval函数
    eval()对表达式求值,后者可以为字符串或内建函数complie()创建的预编译代码对象。
    eval(source[, globals[, locals]])
    第二个和第三个参数,都为可选的,分别代表了全局和局部名字空间中的对象。如果给出这两个参数,globals 必须是个字典,locals可以是任意的映射对象,比如,一个实现了__getitem__()方法的对象。(在2.4 之前,local 必须是一个字典)如果都没给出这两个参数,分别默认为globals()和locals()返回的对象,如果只传入了一个全局字典,那么该字典也作为locals 传入。

1
2
>>> eval('100 + 200')
300





3.exec语句
    exec 语句执行代码对象或字符串形式的python 代码。
    exec obj
    被执行的对象(obj)可以只是原始的字符串,比如单一语句或是语句组,它们也可以预编译成
一个代码对象(分别用'single'和'exec"参数)。

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> exec """
... x = 0
... print 'x is currently:', x
... while x < 5:
... x += 1
... print 'incrementing x to:', x
... """
x is currently: 0
incrementing x to: 1
incrementing x to: 2
incrementing x to: 3
incrementing x to: 4
incrementing x to: 5




    最后, exec 还可以接受有效的python 文件对象。如果我们用上面的多行代码创建一个叫xcount.py 的文件,那么也可以用下面的方法执行相同的代码

1
2
3
4
5
6
7
8
>>> f = open('xcount.py') # open the file
>>> exec f # execute the file
x is currently: 0
incrementing x to: 1
incrementing x to: 2
incrementing x to: 3
incrementing x to: 4
incrementing x to: 5



页: [1]
查看完整版本: python compile、eval、exec内建函数