Categories
Python Answers

How to get real time output using subprocess with Python?

Spread the love

Sometimes, we want to get real time output using subprocess with Python.

In this article, we’ll look at how to get real time output using subprocess with Python.

How to get real time output using subprocess with Python?

To get real time output using subprocess with Python, we loop through the lines that are returned with the iterator that we get with stdout.readline.

For instance, we write

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)
for line in iter(p.stdout.readline, b''):
    print(line)
p.stdout.close()
p.wait()

to call Popen with the cmd command string to run.

And we set stdout to subprocess.PIPE and bufsize to 1 to get the output.

Then we show the output with

for line in iter(p.stdout.readline, b''):
    print(line)

And then we call close to stop reading from stdout.

Conclusion

To get real time output using subprocess with Python, we loop through the lines that are returned with the iterator that we get with stdout.readline.

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 *