在生成和运行子进程时显示进度 [英] showing progress while spawning and running subprocess
问题描述
我需要在生成和运行子进程时显示一些进度条或其他东西.我怎么能用python做到这一点?
I need to show some progress bar or something while spawning and running subprocess. How can I do that with 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()
我可以用这段代码生成子进程,但我需要在每一秒过去时打印出一些东西.
I could spawn subprocess with this code, but I need to print out something when each second is passing.
推荐答案
由于子进程调用是阻塞的,所以在等待时打印出来的一种方法是使用多线程.下面是一个使用线程的例子._Timer:
Since the subprocess call is blocking, one way to print something out while waiting would be to use multithreading. Here's an example using 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() 函数.
On an unrelated note, calling stdout.read() while using multiple pipes can lead to deadlock. The subprocess.communicate() function should be used instead.
这篇关于在生成和运行子进程时显示进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!