2009-06-12 77 views
21

我想在一個線程內使用子進程模塊和Popen啓動'rsync'。在我調用rsync之後,我還需要讀取輸出。我正在使用通信方法來讀取輸出。當我不使用線程時,代碼運行正常。看來,當我使用線程時,它掛在通信調用上。我注意到的另一件事是,當我設置shell = False時,在線程中運行時我從通信中得不到任何回報。Python Subprocess.Popen從線程

回答

33

您沒有提供任何代碼,我們來看看,但這裏的,做類似的東西,以一個樣品你的描述:

import threading 
import subprocess 

class MyClass(threading.Thread): 
    def __init__(self): 
     self.stdout = None 
     self.stderr = None 
     threading.Thread.__init__(self) 

    def run(self): 
     p = subprocess.Popen('rsync -av /etc/passwd /tmp'.split(), 
          shell=False, 
          stdout=subprocess.PIPE, 
          stderr=subprocess.PIPE) 

     self.stdout, self.stderr = p.communicate() 

myclass = MyClass() 
myclass.start() 
myclass.join() 
print myclass.stdout 
+0

是的,這正是我正在做的。我想要讀取線程內的輸出。我也應該注意到我正在使用Python 2.3。我已經從2.4獲得了一個子進程的副本。 – noahd 2009-06-12 04:55:46

+0

然後請將此標記爲「已回答」 – 2009-06-12 12:11:17

9

這裏是不使用線程有很大的實現: constantly-print-subprocess-output-while-process-is-running

import subprocess 

def execute(command): 
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
    output = '' 

    # Poll process for new output until finished 
    for line in iter(process.stdout.readline, ""): 
     print line, 
     output += line 


    process.wait() 
    exitCode = process.returncode 

    if (exitCode == 0): 
     return output 
    else: 
     raise Exception(command, exitCode, output) 

execute(['ping', 'localhost'])