奇怪的未定义变量 python3

weird undefined variable python3

我正在尝试动态加载 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'])