簡體   English   中英

在生成和運行子流程時顯示進度

[英]showing progress while spawning and running subprocess

我需要在生成和運行子流程時顯示一些進度條或其他內容。 如何使用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()

我可以使用此代碼生成子流程,但是每過一秒鍾我就需要打印出一些內容。

由於子進程調用處於阻塞狀態,因此在等待時打印出某種內容的一種方法是使用多線程。 這是使用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()函數。

據我所知,您需要做的就是將這些讀取延遲並打印在一個循環中-是否必須精確到一秒鍾或大約一秒鍾?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM