2015-09-25 26 views
0

我創建了incl.pyml.py。   incl.py將從幾個目錄中的一個目錄加載,每個目錄都包含這樣一個文件incl.py。   ml.pyincl.py通過read()exec()的「主」加載。  每個incl.py預計包含一組具有相同名稱和接口但可能具有不同行爲的函數。線程exec-utes成功的另一個python文件,但不知道包含的功能

ml.py啓動一個或多個線程。  每個線程應該從其個人目錄加載incl.py。  加載工作正常,但是,加載的函數似乎不知道該線程。

內容incl.py

內容的
def printIncluded (parameter): 
    print (parameter) 

ml.py

import threading 

def threadContent (parameter): 
    exec (open ("incl.py").read()) 
    printIncluded (parameter) 

thread = threading.Thread (target = threadContent, args = (("loaded from thread"),)) 
thread.start() 

只要我不使用線程它的作品,例如用以下內容ml.py

exec (open ("incl.py").read()) 
printIncluded ("directly loaded") 

當在線程中工作時,需要考慮什麼exec()

回答

0

我在python globals: import vs. execfile找到了有用的提示。

擴展聲明

exec (open ("incl.py").read()) 

exec (open ("incl.py").read(), globals()) 

使得它的工作。但是,我似乎還沒有對地方和全球範圍的精確想象以及爲什麼這樣做。所以,關於「爲什麼」這個方面問題仍然存在。

除此之外,通過閱讀其他一些答案,我的印象是使用導入是由兩個真正的蟒蛇首選,但我不明白爲什麼(第二個)。使用read()exec()至少編碼似乎比構建長sys路徑擴展更簡單。