2009-06-12 69 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'])