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