我正在尝试动态加载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']
所以CCD_ 4存在。
后一行:
print(test_list)
显示回溯:
NameError: name 'test_list' is not defined
我错过了什么?
不能使用exec()
(或eval()
)设置局部变量;本地命名空间被高度优化。
您看到的是locals()
字典,它是本地名称空间的单向反射;该名称已添加到该字典中,但未添加到真正的命名空间中。
请使用专用名称空间:
namespace = {}
exec(open(test_file).read(), namespace)
print(namespace['test_list'])