简体   繁体   English

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

[英]showing progress while spawning and running subprocess

I need to show some progress bar or something while spawning and running subprocess. 我需要在生成和运行子流程时显示一些进度条或其他内容。 How can I do that with python? 如何使用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. 我可以使用此代码生成子流程,但是每过一秒钟我就需要打印出一些内容。

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: 这是使用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. 不相关的说明是,在使用多个管道时调用stdout.read()可能导致死锁。 The subprocess.communicate() function should be used instead. 应该改用subprocess.communicate()函数。

据我所知,您需要做的就是将这些读取延迟并打印在一个循环中-是否必须精确到一秒钟或大约一秒钟?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM