python - 奇怪的 undefined variable python3

标签 python load python-3.4 nameerror

我正在尝试动态加载 python 文件并检索其变量。

这是我的代码:

test_files = glob.glob("./test/*.py")
for test_file in test_files:
    exec(open(test_file).read())
    print(dir())
    print(test_list)

test_file 是我要检索的共享变量。

print(dir()) 显示:['test_file', 'test_files', 'test_list'] 所以 test_list 存在。

之后的行:

print(test_list) 显示回溯:

NameError: name 'test_list' is not defined

我错过了什么?

最佳答案

您不能使用exec()(或eval())来设置局部变量;本地命名空间经过高度优化。

你看到的是locals()字典,它是本地命名空间的单向反射;该名称已添加到该字典中,但没有添加到真正的命名空间中。

改用专用命名空间:

namespace = {}
exec(open(test_file).read(), namespace)
print(namespace['test_list'])

关于python - 奇怪的 undefined variable python3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28740457/

相关文章:

python - 使用 python 更改嵌套列表中的值

python - 光学字符识别多行检测

python - python中字符串的冗长 boolean 搜索

python - 将 MultiIndex 数据框 reshape 为表格格式

ruby-on-rails - 无法加载此类文件 - sqlite3/sqlite3_native(LoadError)

css - Firefox 上的 Flex loadStyleDeclarations 错误 2035

python - 将 os.path.join 与 os.path.getsize 一起使用,返回 FileNotFoundError

python-3.4 - 导入错误: cannot import name 'html'

javascript - 加载ajax后滚动到页面末尾

python - 从 Python 脚本更改环境变量