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

0 投票
2 回答
3316 浏览
提问于 2025-04-16 14:23

我想在启动和运行子进程的时候显示一个进度条或者类似的东西。
我该怎么用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

从我看来,你只需要把那些读取操作放在一个循环里,加上延迟和打印就行了。这个延迟一定要精确到一秒钟吗,还是说大概一秒就可以?

6

因为子进程调用是阻塞的,也就是说在等待的时候程序会停下来不动,所以一种解决办法是使用多线程。下面是一个使用 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() 函数。

撰写回答