exec 关键字在 python 中有什么作用? [英] what does the exec keyword do in python?
问题描述
code = compile('a = 1 + 2', '', 'exec')执行代码打印一个3
它是如何打印 3 的?有人能告诉我它的确切工作原理吗?
因此 exec 语句可用于执行存储在字符串中的代码.这允许您将代码存储在字符串中.自然地,所有对字符串有效的操作都可以完成.如下所示:
注意:exec
是python 2.7x上的语句,3.x上的函数
随机导入statement = 'print "%s"%(random.random());执行语句
输出:
<预><代码>>>>运行文件(...)0.215359778598>>>运行文件(...)0.702406617438>>>运行文件(...)0.455131491306它可以在测试复杂的数学函数时派上用场.例如:
定义 someMath(n,m,r):return (n**m)//r
随机导入test = 'print "结果为:", someMath(random.random(),random.random(),random.random())'对于范围内的我(20):执行测试
输出:
结果是:1.0结果是:70.0结果是:1.0结果是:2.0结果是:1.0结果是:1.0结果是:0.0结果是:11.0...
code = compile('a = 1 + 2', '<string>', 'exec')
exec code
print a
3
How it prints 3?, Can anybody tell me the exact working of it?
So the exec statement can be used to execute code stored in strings. This allows you to store code in strings. Naturally all manipulations that are valid on strings can be done. This is demonstrated below:
Note: exec
is a statement in python 2.7x and a function on 3.x
import random
statement = 'print "%s"%(random.random());
exec statement
Output:
>>> runfile(...)
0.215359778598
>>> runfile(...)
0.702406617438
>>> runfile(...)
0.455131491306
See also: Difference between eval, exec and compile
It can come in pretty handy while testing complex math functions. For instance:
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
Output:
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
...
这篇关于exec 关键字在 python 中有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!