showing progress while spawning and running subprocess

六眼飞鱼酱① 提交于 2019-12-01 13:09:27

问题


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.


回答1:


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()

On an unrelated note, calling stdout.read() while using multiple pipes can lead to deadlock. The subprocess.communicate() function should be used instead.




回答2:


As far as I see it all you need to do is put those reads in a loop with a delay and a print - does it have to be precisely a second or around about a second?



来源:https://stackoverflow.com/questions/5429577/showing-progress-while-spawning-and-running-subprocess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!