exec关键字在python中做了什么?

时间:2015-04-28 10:14:09

标签: python python-2.7 python-3.x

code = compile('a = 1 + 2', '<string>', 'exec')
exec code
print a
3

它如何打印3?,有人可以告诉我它的确切工作吗?

2 个答案:

答案 0 :(得分:1)

Exec语句用于执行string中包含的Python代码。然后a = 1 + 2 = 3.

更多信息: What's the difference between eval, exec, and compile in Python?

答案 1 :(得分:1)

因此exec语句可用于执行存储在字符串中的代码。这允许您将代码存储在字符串中。当然,所有对字符串都有效的操作都可以完成。这在下面说明:

注意:exec是python 2.7x中的语句和3.x

上的函数
import random
statement = 'print "%s"%(random.random());
exec statement

<强>输出:

>>> runfile(...)
0.215359778598
>>> runfile(...)
0.702406617438
>>> runfile(...)
0.455131491306

另请参阅:Difference between eval, exec and compile

在测试复杂的数学函数时,它非常方便。例如:

def someMath(n,m,r):     return(n ** m)// r

import random
test = 'print "The result of is: ", someMath(random.random(),random.random(),random.random())'
for i in range(20):
    exec test

<强>输出:

The result of is : 1.0
The result of is :  70.0
The result of is :  1.0
The result of is :  2.0
The result of is :  1.0
The result of is :  1.0
The result of is :  0.0
The result of is :  11.0
...