在产生和运行子进程时显示进度

时间:2011-03-25 07:14:36

标签: python subprocess progressdialog

我需要在生成和运行子进程时显示一些进度条或其他内容。 我怎么能用python做到这一点?

import subprocess

cmd = ['python','wait.py']
p = subprocess.Popen(cmd, bufsize=1024,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.stdin.close()
outputmessage = p.stdout.read() #This will print the standard output from the spawned process
message = p.stderr.read()

我可以用这段代码生成子进程,但是我需要在每一秒传递时打印出来。

2 个答案:

答案 0 :(得分:5)

由于子进程调用是阻塞的,因此在等待时打印出一些东西的一种方法是使用多线程。这是使用threading._Timer:

的示例
import threading
import subprocess

class RepeatingTimer(threading._Timer):
    def run(self):
        while True:
            self.finished.wait(self.interval)
            if self.finished.is_set():
                return
            else:
                self.function(*self.args, **self.kwargs)


def status():
    print "I'm alive"
timer = RepeatingTimer(1.0, status)
timer.daemon = True # Allows program to exit if only the thread is alive
timer.start()

proc = subprocess.Popen([ '/bin/sleep', "5" ])
proc.wait()

timer.cancel()

在一个不相关的说明中,在使用多个管道时调用stdout.read()会导致死锁。应该使用subprocess.communicate()函数。

答案 1 :(得分:0)

据我所知,你需要做的就是将这些读取放在一个带有延迟和打印的循环中 - 它必须恰好是一秒或大约一秒钟吗?