在 Python 3 中执行以下操作没有错误:
code = """
import math
def func(x):
return math.sin(x)
func(10)
"""
_globals = {}
exec(code, _globals)
但是,如果我也尝试捕获局部变量 dict ,它会失败并显示NameError
:
>>> _globals, _locals = {}, {}
>>> exec(code, _globals, _locals)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-9-aeda81bf0af1> in <module>()
----> 1 exec(code, {}, {})
<string> in <module>()
<string> in func(x)
NameError: name 'math' is not defined
为什么会发生这种情况,如何在捕获全局变量和局部变量的同时执行此代码?