Sub topic 12
Reading output line by line as it is produced
subprocess.run returns only after the child exits. For a build, a log tail, or a long job with progress messages, you often want each line the moment the child writes it. This chapter shows how to do that with Popen, and why lines sometimes arrive late or all at once.
Prerequisites
This chapter assumes you have read the earlier chapters on subprocess.run, capturing output, and the basics of Popen. You should also know that a pipe is a buffer between two processes, and that text mode decodes bytes into str.
Why run() is not enough
With capture_output=True, run collects everything and hands it to you at the end. Nothing is visible while the child works, and a chatty child holds all its output in memory. Streaming fixes both problems. You start the child with Popen, ask for a pipe on its standard output, and read from that pipe while the child is still running.
The basic streaming loop
import subprocess
import sys
with subprocess.Popen(
[sys.executable, "-u", "-c", "for i in range(3): print(i)"],
stdout=subprocess.PIPE,
text=True,
) as proc:
for line in proc.stdout:
print("got", line.rstrip())
print("exit code", proc.returncode)Three things happen here:
stdout=subprocess.PIPEmakesproc.stdouta readable file object connected to the child's output.- Iterating over
proc.stdoutyields one line at a time. The loop blocks until a full line arrives and ends when the child closes its output, usually by exiting. - Leaving the
withblock closes the pipe and waits for the child, soproc.returncodeis set afterwards.
Each line keeps its trailing newline, which is why the example calls rstrip().
Why output may arrive late: the child's buffering
Streaming only works if the child actually sends data promptly. A program usually writes to a terminal line by line. When its output is a pipe, many programs switch to block buffering and send data only when an internal buffer of several kilobytes fills or the program exits. Your loop then sees nothing for a long time, followed by a burst.
You control the parent side but not always the child. These are the usual fixes for Python children:
- Start the child with
python -u, as in the examples above. - Set
PYTHONUNBUFFERED=1in the child's environment, using theenvargument you saw earlier. - Use
print(..., flush=True)in the child's code.
For other programs, look for a line-buffering option. For example, grep --line-buffered and tail -f behave well, and tools like stdbuf on Linux can force buffering modes for many C programs. Nothing in the parent can make a block-buffered child flush sooner.
Including standard error
A child's error messages are often what you most want to see in order with its normal output. If you read only stdout, the stderr text goes to your terminal unmixed. To merge the two streams into one pipe, redirect stderr into stdout:
import subprocess
import sys
child_code = (
"import sys\n"
"print('out 1', flush=True)\n"
"print('err 1', file=sys.stderr, flush=True)\n"
"print('out 2', flush=True)\n"
)
with subprocess.Popen(
[sys.executable, "-c", child_code],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
) as proc:
for line in proc.stdout:
print("line:", line.rstrip())Because both streams share one pipe and the child flushes each write, the lines arrive in the order they were written. You lose the ability to tell which stream a line came from. If you need that, you need two pipes read at once, which is covered below.
Text mode and line endings
In text mode, Python decodes the bytes and uses universal newlines. \n, \r\n, and a bare \r all end a line. Two consequences follow:
- Windows-style output arrives with clean
\nendings. - Progress bars that redraw using
\rshow up as many separate "lines", one per update.
In binary mode (omit text=True), iteration yields bytes and splits only at b"\n". A carriage-return progress bar then arrives as one long line that ends only when the program prints a real newline. Binary mode also avoids decoding errors on output that is not valid text. You can pass errors="replace" in text mode to substitute bad bytes instead of raising UnicodeDecodeError. Set encoding= explicitly when the child does not use your locale's default.
Stopping early and cleaning up
You may want to stop reading before the child finishes, for example when you find an error marker. Breaking out of the loop does not stop the child. Leaving the with block closes your end of the pipe and then waits, and a child that keeps running will make that wait last until it exits. Terminate it first:
import subprocess
import sys
child_code = (
"import time\n"
"for i in range(100):\n"
" print(i, flush=True)\n"
" time.sleep(0.2)\n"
)
with subprocess.Popen(
[sys.executable, "-c", child_code],
stdout=subprocess.PIPE,
text=True,
) as proc:
for line in proc.stdout:
number = int(line)
print("got", number)
if number == 2:
proc.terminate()
break
print("exit code", proc.returncode)terminate() asks the child to stop. On Linux and macOS it sends SIGTERM, and the exit code is then -15, the negative of the signal number. On Windows the exit code is 1. If a child ignores the request, kill() forces it.
A reusable generator
The pattern is common enough to wrap in a generator. This version merges stderr, stops the child if the consumer abandons the loop or an exception occurs, and raises CalledProcessError after the output ends if the exit code was not zero.
import subprocess
import sys
def stream_lines(cmd):
with subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
) as proc:
try:
for line in proc.stdout:
yield line.rstrip("\n")
except BaseException:
proc.terminate()
raise
if proc.returncode:
raise subprocess.CalledProcessError(proc.returncode, cmd)
for text in stream_lines([sys.executable, "-u", "-c", "for i in range(3): print(i)"]):
print("line", text)The except BaseException clause also catches GeneratorExit, which Python raises inside the generator when the caller breaks out of its loop early. The check for the exit code sits after the with block because returncode is only reliable once the child has been waited for.
Limits of this approach
Reading from a pipe has no timeout. for line in proc.stdout blocks until the child writes a line or closes the pipe, and Popen offers no per-read time limit. If the child hangs silently, so does your loop. The options are:
- Read in a background thread and pass lines to the main thread through a
queue.Queue, usingqueue.get(timeout=...). - Use
selecton the pipe, which works on Linux and macOS but not for pipes on Windows. - Use
asynciosubprocesses, where you can wrap reads inasyncio.wait_for.
The last chapter of this tutorial gives a short look at the asyncio route.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Nothing appears, then everything at once | The child block-buffers output on a pipe | Use `-u`, `flush=True`, or the program's line-buffering option |
| Loop never ends | The child is still running or a grandchild holds the pipe open | Check what the child does, and call `terminate()` when appropriate |
| Program freezes with large `stderr` output | Unread `stderr=PIPE` filled up | Use `stderr=subprocess.STDOUT`, a file, or `DEVNULL` |
| Progress bar shows as hundreds of lines | Text mode splits on `\r` | Read in binary mode and split yourself |
| `returncode` is `None` inside the loop | The child has not been waited for | Read it after the `with` block, or call `proc.wait()` |
| `UnicodeDecodeError` | Output is not in the expected encoding | Set `encoding=` or `errors="replace"`, or read bytes |
Exercises
Exercise
A script of yours runs Popen([sys.executable, "worker.py"], stdout=PIPE, text=True) and loops over proc.stdout. The worker prints a status line every second, but your loop receives nothing for minutes and then gets 300 lines together. What is the most likely cause, and what are two ways to fix it?
Show answer
The worker is block-buffering its output because stdout is a pipe, so the data is not sent until the buffer fills or the program exits. Fix it by running the worker with python -u (or setting PYTHONUNBUFFERED=1 in the child's environment), or by adding flush=True to its print calls. Changing bufsize in the parent does not help, because it only affects the parent's side of the pipe.
Exercise
You want to show a child's regular output and its error messages in the order they were produced, and you do not need to know which line came from which stream. Which Popen arguments do you use, and what is the trade-off?
Show answer
Pass stdout=subprocess.PIPE and stderr=subprocess.STDOUT, then iterate over proc.stdout. Both streams share one pipe, so ordering is preserved (provided the child flushes). The trade-off is that you can no longer tell which lines were standard error. It also avoids the deadlock that comes from leaving a second pipe unread.
Exercise
Write a loop that starts [sys.executable, "-u", "-c", "for i in range(1000): print(i)"], prints lines until it sees the line 5, then stops the child. What exit code do you expect on Linux, and why might it differ from the code of a child that finished normally?
Show answer
Use with subprocess.Popen(cmd, stdout=subprocess.PIPE, text=True) as proc:, loop over proc.stdout, and when line.strip() == "5" call proc.terminate() and break. On Linux the exit code is -15, because returncode is the negative signal number when a process is killed by a signal, whereas a normal finish gives 0. (If the child had already exited, the code could be 0.)