showing progress while spawning and running subprocess

后端 未结 2 685
傲寒
傲寒 2021-01-17 04:00

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\',\'w         


        
2条回答
  •  一生所求
    2021-01-17 04:33

    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.

提交回复
热议问题