在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