Sub topic 14
Avoiding pipe buffer deadlocks
This chapter assumes you can use Popen, know what standard output and standard error are, and have seen communicate() and line-by-line streaming.
Why a pipe can fill up
When you pass stdout=subprocess.PIPE, the operating system connects the child to your program through a pipe. A pipe is a fixed-size buffer in the kernel. On Linux the default is 64 KiB. Other systems use different sizes.
If the child writes faster than you read, the buffer fills. The child's next write then blocks until you read some data. This is normal flow control. It becomes a deadlock when you are also waiting for the child to finish. The child waits for you to read, and you wait for the child to exit, so neither can continue.
The classic mistake
This program hangs. The child prints far more than a pipe holds, and the parent calls wait() without reading anything.
import subprocess
import sys
proc = subprocess.Popen(
[sys.executable, "-c", "print('x' * 1_000_000)"],
stdout=subprocess.PIPE,
text=True,
)
proc.wait() # Deadlock: nobody is reading the pipe.
print("never reached")Do not run this without a timeout of your own. The same problem occurs with stderr=subprocess.PIPE.
Fix 1: use communicate
communicate() reads stdout and stderr until both reach end of file, then waits for the process. It also writes any input you give it. It handles several pipes at once without blocking on any one of them.
import subprocess
import sys
proc = subprocess.Popen(
[sys.executable, "-c", "print('x' * 1_000_000)"],
stdout=subprocess.PIPE,
text=True,
)
output, _ = proc.communicate()
print(len(output.strip()), proc.returncode)This prints 1000000 0. subprocess.run(..., capture_output=True) calls communicate() internally, so it is also safe. The cost is that all output is held in memory.
Fix 2: read as the output arrives
If the output is large or you want to process it live, read it continuously. Reading from proc.stdout in a loop keeps the pipe drained.
import subprocess
import sys
count = 0
with subprocess.Popen(
[sys.executable, "-c", "print('x' * 1_000_000)"],
stdout=subprocess.PIPE,
text=True,
) as proc:
for line in proc.stdout:
count += len(line.strip())
print(count, proc.returncode)Two pipes at once
Reading only stdout is not enough if stderr is also a pipe. The child can fill the stderr pipe while you wait on stdout. You have three safe options:
| Option | How | Trade-off |
|---|---|---|
| Merge streams | `stderr=subprocess.STDOUT` | One stream, so you lose the distinction between normal and error output |
| Use `communicate()` | Reads both pipes together | Everything is buffered in memory |
| Discard or redirect | `stderr=subprocess.DEVNULL` or a file object | You cannot read the discarded output |
Writing output to a file is often the simplest way to handle large output:
import subprocess
import sys
import tempfile
with tempfile.TemporaryFile("w+") as log:
subprocess.run(
[sys.executable, "-c", "print('x' * 1_000_000)"],
stdout=log,
check=True,
)
log.seek(0)
print(len(log.read().strip()))The child writes straight to the file, so no pipe can fill.
Common errors
- Calling
proc.wait()afterstdout=PIPE. Usecommunicate()instead. - Reading all of stdout, then all of stderr. A large stderr can still block the child.
- Sending a large
inputwhile also expecting large output. Usecommunicate(input=...), which does both safely.
Exercise
A script starts Popen(cmd, stdout=PIPE, stderr=PIPE), reads every line of proc.stdout, and only then reads proc.stderr. It hangs on some inputs. Why, and what is the smallest change that fixes it?
Show answer
The child writes enough to stderr to fill that pipe. It blocks on the write, so it never closes stdout, and the loop over stdout never ends. The smallest fix is to pass stderr=subprocess.STDOUT so both streams share one pipe, or to call communicate(), which reads both pipes together.