1.Python3 compile()函数
exec 语句或者内建函数eval()来执行这些对象或者对它们进行求值。
一个很重要的观点是:
第一参数代表了要编译的
可求值表达式:
Python
>>> eval_code = compile('100 + 200', '', 'eval')
>>> eval(eval_code)
300
1
2
3
>>>eval_code=compile('100 + 200','','eval')
>>>eval(eval_code)
300
可执行语句组:
Python
>>> 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
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')
>>>execexec_code
Counthowmanynumbers?6
0
1
2
3
4
5
2.eval函数
eval()对表达式求值,后者可以为字符串或内建函数complie()创建的预编译代码对象。
eval(source[, globals[, locals]])
第二个和第三个参数,都为可选的,分别代表了全局和局部名字空间中的对象。如果给出这两个参数,globals 必须是个字典,locals可以是任意的映射对象,比如,一个实现了__getitem__()方法的对象。(在2.4 之前,local 必须是一个字典)如果都没给出这两个参数,分别默认为globals()和locals()返回的对象,如果只传入了一个全局字典,那么该字典也作为locals 传入。
Python
>>> eval('100 + 200')
300
1
2
>>>eval('100 + 200')
300
3.exec语句
exec 语句执行代码对象或字符串形式的
Python
>>> 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
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
... """
xiscurrently:0
incrementingxto:1
incrementingxto:2
incrementingxto:3
incrementingxto:4
incrementingxto:5
最后, exec 还可以接受有效的python 文件对象。如果我们用上面的多行代码创建一个叫xcount.py 的文件,那么也可以用下面的方法执行相同的代码
Python
>>> 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
2
3
4
5
6
7
8
>>>f=open('xcount.py')# open the file
>>>execf# execute the file
xiscurrently:0
incrementingxto:1
incrementingxto:2
incrementingxto:3
incrementingxto:4
incrementingxto:5