Sometimes, we want to constantly print Subprocess output while process is running with Python.
In this article, we’ll look at how to constantly print Subprocess output while process is running with Python.
How to constantly print Subprocess output while process is running with Python?
To constantly print Subprocess output while process is running with Python, we can loop through stdout and call print in the loop.
For instance, we write
from subprocess import Popen, PIPE, CalledProcessError
with Popen(cmd, stdout=PIPE, bufsize=1, universal_newlines=True) as p:
for line in p.stdout:
print(line, end='')
if p.returncode != 0:
raise CalledProcessError(p.returncode, p.args)
to call Popen with the cmd command we want to run.
Then we have a for loop that loops through p.stdout to get the output lines.
In the loop, we call print to print the line.
Conclusion
To constantly print Subprocess output while process is running with Python, we can loop through stdout and call print in the loop.