我正在尝试使用 eval() 执行一些函数,我需要为它们创建某种运行环境。文档中说您可以将全局变量作为第二个参数传递给 eval()。
但在我的情况下似乎不起作用。这是简化的示例(我尝试了两种方法,声明变量全局和使用 globals(),但两者都不起作用):
文件script.py:
import test
global test_variable
test_variable = 'test_value'
g = globals()
g['test_variable'] = 'test_value'
eval('test.my_func()', g)
文件test.py:
def my_func():
global test_variable
print repr(test_variable)
我得到:
NameError: global name 'test_variable' is not defined.
我应该怎么做才能将 test_variable
传递给 my_func()
?假设我不能将它作为参数传递。
最佳答案
test_variable 在 test.py 中应该是全局的。您收到名称错误是因为您试图声明一个尚不存在的全局变量。
所以你的 my_test.py 文件应该是这样的:
test_variable = None
def my_func():
print test_variable
然后从命令提示符运行它:
>>> import my_test
>>> eval('my_test.my_func()')
None
>>> my_test.test_variable = 'hello'
>>> my_test.test_variable
'hello'
>>> eval('my_test.my_func()')
hello
通常使用 eval() 和全局变量是一种不好的形式,因此请确保您知道自己在做什么。
关于Python 的 eval() 和 globals(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/729248/