在python2中,exec的调用方式:
scope = {}
exec 'x = 2' in scope
在python3中,exec的调用方式:
scope = {}
exec ('x = 2', scope)
结果如下:
scope['x']
2
scope
{'x': 2, '__builtins__': ...}
在使用exec后,scope中多了__builtins__这个key,指的是python中的内建模块,也可以自己指定,如果为空的话,则无法继续 使用python的内建函数,如十月狐狸在博客(Python内置函数(20)——exec)http://www.cnblogs.com/sesshoumaru/)中的例子:
>>> g = {}
>>> exec('a = abs(-1)',g)
>>>
>>> g = {'__builtins__':{}}
>>> exec('a = abs(-1)',g) #不能使用内置函数了
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
exec('a = abs(-1)',g)
File "<string>", line 1, in <module>
NameError: name 'abs' is not defined