Categories
Python Answers

How to constantly print Subprocess output while process is running with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *