Show progress with spawning and starting a subprocess

I need to show some progress bar or something else when spawning and starting the subprocess. How can I do this 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 generate a subprocess using this code, but I need to print something when every second passes.

0
source share
2 answers

Since the subprocess call is blocked, one way to print something while waiting is to use multithreading. Here is 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() 

In an unrelated note, calling stdout.read () when using multiple pipes can lead to a deadlock. Instead, use the subprocess.communicate () function.

+4
source

As far as I can see, all you have to do is put those that read in a loop with a delay and print - should this be exactly the second or about a second?

0
source

Source: https://habr.com/ru/post/1345272/


All Articles