Skip to main content
 首页 » 编程设计

python之奇怪的 undefined variable python3

2024年10月25日14qq号

我正在尝试动态加载 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 的一种单向反射(reflect);该名称已添加到该字典中,但未添加到实际 namespace 中。

改为使用专用命名空间:

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