【发布时间】:2010-11-02 08:46:47
【问题描述】:
我正在尝试使用子进程模块和 Popen 在线程内启动“rsync”。在我调用 rsync 之后,我还需要读取输出。我正在使用通信方法来读取输出。当我不使用线程时,代码运行良好。看来,当我使用线程时,它会挂在通信调用上。我注意到的另一件事是,当我设置 shell=False 时,我在线程中运行时不会从通信中得到任何回报。
【问题讨论】:
标签: python multithreading subprocess rsync
我正在尝试使用子进程模块和 Popen 在线程内启动“rsync”。在我调用 rsync 之后,我还需要读取输出。我正在使用通信方法来读取输出。当我不使用线程时,代码运行良好。看来,当我使用线程时,它会挂在通信调用上。我注意到的另一件事是,当我设置 shell=False 时,我在线程中运行时不会从通信中得到任何回报。
【问题讨论】:
标签: python multithreading subprocess rsync
您没有提供任何代码供我们查看,但这里有一个与您描述的类似的示例:
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
【讨论】:
这是一个很好的不使用线程的实现: 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'])
【讨论】:
process.stdout.readline()。
\r 后面重复打印进度,则将universal_newlines=True 添加到Popen 命令很有用。如果没有universal_newlines 选项,您需要等到最后的\n 才能获得一个巨大的字符串(包含连接在一起的所有进度条)。