我正在尝试使用eval()执行许多函数,我需要为它们创建一些运行环境.在文档中可以说你可以将全局变量作为第二个参数传递给eval().
但似乎在我的情况下不起作用.这是简单的例子(我尝试了两种方法,声明变量global和使用globals(),两者都不起作用):
import test
global test_variable
test_variable = 'test_value'
g = globals()
g['test_variable'] = 'test_value'
eval('test.my_func()', g)
Run Code Online (Sandbox Code Playgroud)
def my_func():
global test_variable
print repr(test_variable)
Run Code Online (Sandbox Code Playgroud)
我得到了:
NameError:未定义全局名称"test_variable".
我应该怎么做才能将其传递test_variable给my_func()?假设我无法将其作为参数传递.