Python的eval()和globals() [英] Python's eval() and globals()
问题描述
我正在尝试使用eval()执行许多功能,并且需要创建某种环境以使其运行.在文档中说,您可以将全局变量作为第二个参数传递给eval().
I'm trying to execute a number of functions using eval(), and I need to create some kind of environment for them to run. It is said in documentation that you can pass globals as a second parameter to eval().
但是对于我来说似乎不起作用.这是一个简化的示例(我尝试了两种方法,声明变量global和使用globals(),但两种方法都不起作用):
But it seems to not work in my case. Here's the simpified example (I tried two approaches, declaring variable global and using globals(), and both do not work):
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:未定义全局名称"test_variable".
NameError: global name 'test_variable' is not defined.
我应该怎么做才能将test_variable
传递给my_func()
?假设我不能将其作为参数传递.
What should I do to pass that test_variable
into my_func()
? Assuming I can't pass it as a parameter.
推荐答案
test_variable 在test.py中应该是全局的.之所以出现名称错误,是因为您试图声明一个尚不存在的全局变量.
test_variable should be global in test.py. You're getting a name error because you're trying to declare a variable global that doesn't yet exist.
因此,您的my_test.py文件应如下所示:
So your my_test.py file should be like this:
test_variable = None
def my_func():
print test_variable
并在命令提示符下运行它:
And running this from the command prompt:
>>> 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()和全局变量是一种不好的形式,因此请确保您知道自己在做什么.
Generally it's bad form to use eval() and globals, so make sure you know what your doing.
这篇关于Python的eval()和globals()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!