Categories
Python Answers

How to read subprocess stdout line by line in Python?

Spread the love

Sometimes, we want to read subprocess stdout line by line in Python?

In this article, we’ll look at how to read subprocess stdout line by line in Python?

How to read subprocess stdout line by line in Python?

To read subprocess stdout line by line in Python, we can call stdout.readline on the returned process object.

For instance, we write:

import subprocess

proc = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)
while True:
    line = proc.stdout.readline()
    if not line:
        break
    print(line.rstrip())

We call subprocess.Popen with a list of strings with the command and command line arguments.

Then we set stdout to subprocess.PIPE to return the output.

Next, we call proc.stdout.readline to return the next line of the stdout output in the while loop.

If line is None, then we stop the loop.

Otherwise, we print the line.

Therefore, we get text like:

b'total 64'
b'-rw-r--r-- 1 runner runner   183 Oct 20 01:10 main.py'
b'-rw-r--r-- 1 runner runner 14924 Oct 19 23:40 poetry.lock'
b'drwxr-xr-x 1 runner runner   126 Oct 19 23:17 __pycache__'
b'-rw-r--r-- 1 runner runner   319 Oct 19 23:39 pyproject.toml'
b'-rw-r--r-- 1 runner runner 12543 Oct 20 00:16 somepic.png'
b'-rw-r--r-- 1 runner runner   197 Oct 19 23:21 strings.json'
b'-rw------- 1 runner runner 18453 Oct 20 00:16 test1.png'

on the screen.

Conclusion

To read subprocess stdout line by line in Python, we can call stdout.readline on the returned process object.

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 *