2015-02-26 96 views
2

我想動態加載一個python文件並檢索它的變量。奇怪的未定義變量python3

這裏是我的代碼:

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 

我錯過了什麼?

+0

這是一個功能呢? –

+0

是的,這裏是我所有的代碼:http://pastie.org/9983986 – Epitouille

回答

2

您不能使用exec()(或eval())設置局部變量;本地命名空間被高度優化。

你在看什麼是locals()字典,單向反映本地命名空間;該名字被添加到該字典中,但不添加到真實名稱空間。

使用專用的命名空間,而不是:

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

它的作品像一個魅力,謝謝 – Epitouille