Python 的 eval() 和 globals()

标签 python eval

我正在尝试使用 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/

相关文章:

javascript - 跟踪 Javascript eval 中错误的源代码行

python - eval函数在python中不起作用

javascript - 与使用 eval 相比,包含 <script> 标签是否有性能提升?

python - 将 Github Actions 与 Lektor CMS 结合使用

javascript - 简化的动态算术运算符

python - 将 xml 文件嵌套到 pandas 数据框

python - 为子域设置 SERVER_NAME 后 flask 中 www 前缀的问题

.net - ASP .NET - Eval() 背后发生了什么?

python - 专门在 seaborn 集群图中更改热图的大小?

python - 在 Mac 上为 PyDev 配置 App Engine 路径