Sub topic 12
Reading output line by line as it is produced
This chapter assumes you know subprocess.run, capture_output, and the basics of Popen from the previous chapter. run waits for the child to finish and returns all its output at once. For a long job, such as a build or a log tail, you often want each line as soon as it appears. Popen gives you that.
Reading from proc.stdout
Start the child with stdout=subprocess.PIPE. Python then exposes proc.stdout as a file-like object. Iterating over it yields one line at a time, and the loop blocks until the next line arrives.
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)The output is:
got 0
got 1
got 2
exit code 0Three details matter here:
text=Truedecodes each line tostr. Without it you getbytes.- Each line keeps its trailing newline, so
rstrip()removes it before printing. - Leaving the
withblock closes the pipes and waits for the child, soproc.returncodeis set afterward.
Why the child needs -u
When a Python program writes to a pipe instead of a terminal, it buffers its output and sends it in large chunks. Your loop would then see nothing until the buffer fills or the child exits. That defeats streaming.
The -u flag turns off this buffering in a child Python interpreter. Other programs have their own switches. For example, grep --line-buffered and stdbuf -oL on Linux ask for line buffering. You cannot fix the child's buffering from the parent. If the program offers no option, you will receive its output in bursts.
Merging stderr into the stream
A child also writes errors to standard error. If you only pipe stdout, error text goes to your terminal and is not in your loop. To read both in order, send stderr into the same pipe:
import subprocess
import sys
code = "import sys; print('out'); print('err', file=sys.stderr)"
with subprocess.Popen(
[sys.executable, "-u", "-c", code],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
) as proc:
for line in proc.stdout:
print("line:", line.rstrip())stderr=subprocess.STDOUT merges the two streams. You cannot tell afterward which line came from which stream. If you need them apart, you must read both at once, which is covered in the chapter on pipe deadlocks.
The flow of data
Stopping early
You do not have to read to the end. If you find what you need, call proc.terminate() and then leave the loop. The with block still waits for the child, so terminate first or the block may wait a long time.
import subprocess
import sys
with subprocess.Popen(
[sys.executable, "-u", "-c", "import time\nwhile True: print('tick'); time.sleep(0.2)"],
stdout=subprocess.PIPE,
text=True,
) as proc:
for count, line in enumerate(proc.stdout, start=1):
print(line.rstrip(), count)
if count == 3:
proc.terminate()
breakCommon mistakes
- Calling
proc.stdout.read()orproc.wait()before the loop.read()waits for all output, which removes the streaming.wait()can hang if the child fills the pipe, as the deadlock chapter explains. - Forgetting
stdout=subprocess.PIPE. Thenproc.stdoutisNoneand the loop raisesTypeError. - Expecting a timeout. The loop has none. A silent child blocks you forever, so use a separate thread or
asyncioif you need one.
Exercise
Your loop over proc.stdout prints nothing for a minute, then prints every line at once when the child exits. The child is a Python script. What is the likely cause, and what is the fix?
Show answer
The child buffers its output because stdout is a pipe, not a terminal. Start it with python -u (or set PYTHONUNBUFFERED=1, or call print with flush=True in the child) so each line is sent as soon as it is written.
Exercise
How do you read a child's standard output and standard error in the order they were written, in a single loop?
Show answer
Start Popen with stdout=subprocess.PIPE and stderr=subprocess.STDOUT, then iterate over proc.stdout. The two streams are merged, so you cannot tell them apart afterward.