【问题标题】:showing progress while spawning and running subprocess在生成和运行子进程时显示进度
【发布时间】:2011-03-25 07:14:36
【问题描述】:

我需要在生成和运行子进程时显示一些进度条或其他内容。 我怎么能用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()

我可以使用这段代码生成子进程,但我需要在每一秒过去时打印出一些东西。

【问题讨论】:

    标签: python subprocess progressdialog


    【解决方案1】:

    由于子进程调用是阻塞的,在等待时打印输出的一种方法是使用多线程。这是一个使用线程的示例。_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() 函数。

    【讨论】:

      【解决方案2】:

      据我所知,您需要做的就是将这些读取放入一个带有延迟和打印的循环中 - 它必须精确到一秒还是大约一秒?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多