2016-10-05 72 views
1

我使用Python 2.7和新的線程。我有一個類文件和運行方法。但是當我創建線程實例時,我看不到調用的run方法。我也計劃在run方法內使用subprocess.Popen,併爲每個文件名獲得stdout進程並打印輸出。線程與子進程

請告訴我我在這裏丟失了什麼run方法被調用。

class FileScanThread(threading.Thread): 
    def __init__(self, myFileName): 
     print("In File Scan Thread") 
     self.mapFile = myFileName 
     #myjar=myFileName 
     self.start() 

    def run(self): 
     print self.mapFile 

    x= FileScanThread("myfile.txt") 
+0

我想,太(x.start()),但run方法不會被調用。 python 2.7有沒有不同的語法? –

回答

4

你忘記調用母類構造函數來指定目標。這不是java,並且run沒有特別的意義。默認情況下,目標是None,線程不執行任何操作。

import threading 

class FileScanThread(threading.Thread): 
    def __init__(self, myFileName): 
     threading.Thread.__init__(self,target=self.run) 
     # another syntax uses "super", which is simpler in python 3 
     # super().__init__(target=self.run) 

     print("In File Scan Thread") 
     self.mapFile = myFileName 
     #myjar=myFileName 
     self.start() 

    def run(self): 
     print(self.mapFile) 

x= FileScanThread("myfile.txt") 

x.join() # when you're done 
1

這會做你想做的。您不會從Thread類中調用__init__

class FileScanThread(threading.Thread): 
    def __init__(self, myFileName): 
     threading.Thread.__init__(self) 
     print("In File Scan Thread") 
     self.mapFile = myFileName 
     #myjar=myFileName 
     self.start() 

    def run(self): 
     print self.mapFile 

x = FileScanThread("myfile.txt") 

我不認爲你必須將目標參數傳遞給它。至少我通常不會這樣做。

輸出:

In File Scan Thread 
myfile.txt 
+0

對,如果你想讓線程運行一個外部函數,你只想使用'target'。在這種情況下,類實例就是線程。 – tdelaney