exec
如果否locals
并globals
通过,则在当前范围内执行。因此,您将模块import sys
导入范围。见代码:sys
importing
>>> def c():
... exec('import sys')
... print(locals())
... print(globals())
...
>>> c()
{'sys': <module 'sys' (built-in)>}
{'__builtins__': <module 'builtins'>, '__package__': None, '__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'c': <function c at 0x7faa068e0320>, 'b': <function b at 0x7faa068e45f0>, 'a': <function a at 0x7faa066abe60>, 'd': <function d at 0x7faa068f6200>, 'inspect': <module 'inspect' from '/usr/lib64/python3.3/inspect.py'>, '__doc__': None}
看,sys
它在本地范围内,但不在全局范围内。但要注意,导入是动态执行的,即使是在本地范围内,也不能在函数中直接调用sys。调用会报错,在全局范围内找不到 sys:
>>> def a():
... exec('import sys')
... if sys:
... return True
... else:
... return False
...
>>> a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in a
NameError: global name 'sys' is not defined
相反,您应该使用locals()
:
>>> def b():
... exec('import sys')
... if locals()['sys']:
... return True
... else:
... return False
...
>>> b()
True
最后,我认为使用exec
不是一个好的选择。就像其他人提到的那样,使用__importing__
.