Sub topic 13
Building a pipeline between two processes
This chapter assumes you can use subprocess.run, you know what Popen is, and you know that a child process has standard input, output and error streams. It shows how to connect the output of one program to the input of another from Python, the way a | b does in a shell. It then covers the places where the Python version differs from the shell version.
What a pipeline is
A pipe is a one-way channel managed by the operating system. One process writes bytes into one end, and another process reads them from the other end. A pipeline chains programs so that each one's standard output becomes the next one's standard input.
You can do this with subprocess.run only by running the first command to completion, capturing all its output in memory, and passing that to the second command through input=. That works for small data, but it holds everything in memory and the two programs never run at the same time. With Popen, both processes run concurrently and the data flows between them without passing through your program.
The basic two-process pipeline
import subprocess
import sys
producer = subprocess.Popen(
[sys.executable, "-c", "print('a b c')"],
stdout=subprocess.PIPE,
)
consumer = subprocess.Popen(
[sys.executable, "-c", "import sys; print(len(sys.stdin.read().split()))"],
stdin=producer.stdout,
stdout=subprocess.PIPE,
text=True,
)
producer.stdout.close()
output, _ = consumer.communicate()
producer.wait()
print(output.strip())This prints 3. Four details matter:
- The producer uses
stdout=subprocess.PIPE. Python creates a pipe and exposes the read end asproducer.stdout. - The consumer passes that file object as
stdin=. The operating system hands the same read end to the second child, so the data goes directly from child to child. producer.stdout.close()closes the parent's copy of the read end. This step is easy to forget, and the next section explains why it matters.consumer.communicate()reads the consumer's output until it ends and waits for the consumer to exit. The producer is waited on separately withproducer.wait(), so it does not stay in the process table as a zombie, a finished process whose exit status nobody has collected.
Only the consumer has text=True. Text mode is a per-process setting that applies to the pipes your program reads or writes. The pipe between the two children carries raw bytes.
Why the parent closes its copy of the pipe
When Popen creates a pipe, the parent holds the read end, and the child holds a copy of it after the new process starts. After you pass producer.stdout to the consumer, there are two read ends: the parent's and the consumer's.
An operating system tells a writer that nobody is listening only when every copy of the read end is closed. If the parent keeps its copy open, the producer is never told that the consumer has exited. In a shell pipeline such as yes | head -n 1, head exits after one line and yes is stopped by the broken pipe. In Python, if you leave the parent's copy open, the producer can block forever on a full pipe, or keep running for as long as it has data.
Closing the parent's copy makes the consumer the only reader. If the consumer exits, the producer's next write fails. In Python that surfaces as BrokenPipeError, and on POSIX systems a program that does not handle it is stopped by the SIGPIPE signal.
A reusable helper for any number of stages
The two-process code generalizes to a loop. The helper below starts every stage, wires each stage to the previous one, reads the final output and returns every exit status.
import subprocess
import sys
def run_pipeline(commands, timeout=None):
procs = []
previous = None
try:
for cmd in commands:
proc = subprocess.Popen(cmd, stdin=previous, stdout=subprocess.PIPE)
if previous is not None:
previous.close()
procs.append(proc)
previous = proc.stdout
output, _ = procs[-1].communicate(timeout=timeout)
codes = [p.wait() for p in procs[:-1]] + [procs[-1].returncode]
return output, codes
except BaseException:
for p in procs:
p.kill()
for p in procs:
p.wait()
if p.stdout:
p.stdout.close()
raise
emit = [sys.executable, "-c", "print('b\\na\\nc')"]
sort_lines = [
sys.executable,
"-c",
"import sys; sys.stdout.write(''.join(sorted(sys.stdin)))",
]
shout = [
sys.executable,
"-c",
"import sys; sys.stdout.write(sys.stdin.read().upper())",
]
output, codes = run_pipeline([emit, sort_lines, shout], timeout=10)
print(output.decode().split())
print(codes)The output is ['A', 'B', 'C'] followed by [0, 0, 0]. The first stage inherits your program's standard input because its stdin is None. Calling .decode().split() avoids a platform difference, because Windows writes \r\n line endings where POSIX writes \n.
The except BaseException block cleans up if anything goes wrong, including a TimeoutExpired from communicate or a KeyboardInterrupt. It kills every child, collects their exit statuses and closes the pipe objects before it re-raises.
Checking every stage, not only the last
A shell reports only the exit status of the last command in a pipeline. If the first command fails and the last one succeeds on empty input, $? says 0. Bash has set -o pipefail to change this. In Python you have all the statuses in a list, so you can apply any rule you like:
output, codes = run_pipeline([emit, sort_lines, shout], timeout=10)
failed = [i for i, code in enumerate(codes) if code != 0]
if failed:
raise RuntimeError(f"pipeline stages failed: {failed}, codes: {codes}")You decide which codes count as failure. Some tools use non-zero codes for meaningful results. For example, grep exits with 1 when it finds no match, which is not an error. Checking per stage lets you accept that code for the grep stage only.
When the consumer stops early
The reason for the parent-side close() shows up when the consumer reads less than the producer can write:
import sys
endless = [sys.executable, "-c", "while True: print('x')"]
first_line = [sys.executable, "-c", "import sys; print(sys.stdin.readline().strip())"]
output, codes = run_pipeline([endless, first_line], timeout=10)
print(output.decode().strip())
print(codes[0] != 0, codes[1])This prints x, then True 0. The consumer reads one line and exits. Because the parent already closed its copy of the read end, the producer's next flush fails with a broken pipe and it exits with a non-zero status. The exact number depends on the platform and Python version, so test for non-zero and not for a particular value. A non-zero status on an upstream stage is the normal result when a downstream stage stops reading early, so you may want to ignore it in that case.
Standard error and deadlocks
The helper leaves stderr alone, so every stage writes errors to your program's own standard error. This is deliberate. If you set stderr=subprocess.PIPE on an intermediate stage, nothing reads that pipe. When it fills (commonly 64 KiB on Linux), the stage blocks on a write and the whole pipeline stalls.
You have three safe options:
- Let stderr be inherited, as the helper does.
- Send it to a file by passing an open file object as
stderr=. - Merge it into the output with
stderr=subprocess.STDOUT, if mixing the streams is acceptable.
Reading several pipes from one thread is the situation the chapter on pipe deadlocks covers. In a pipeline the safe pattern is that exactly one pipe, the final output, is read by your program, and communicate() does that reading.
Pipelines through a shell
A shell can build the pipeline for you:
import subprocess
subprocess.run("echo one two three | wc -w", shell=True, check=True)This is shorter, but it has costs. The shell parses the string, so untrusted text in it creates an injection risk. The behavior depends on the platform's shell. wc does not exist on a default Windows system. By default you get only the last command's exit status. Use shell=True for fixed, trusted strings in scripts that run on one platform. Use the Popen approach when any part of the pipeline comes from outside your program or when you need the status of each stage.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Not closing `producer.stdout` in the parent | The producer is never told the consumer exited, so it may hang or run on | Close the parent's copy after starting the consumer |
| Using `stderr=PIPE` on a middle stage and never reading it | The stage blocks when the pipe fills, stalling the pipeline | Inherit stderr or write it to a file |
| Calling `producer.communicate()` after handing its stdout to the consumer | The two readers compete for the same bytes | Call `communicate()` only on the last process |
| Not waiting on earlier stages | Zombie processes and lost exit statuses | Call `wait()` on every process |
| Checking only the last return code | A failure in an early stage goes unnoticed | Inspect every status |
| Using `text=True` and expecting every pipe to be text | The pipe between children stays bytes | Set text mode on the process whose output you read |
Exercise
You build a pipeline from producer to consumer with Popen. The consumer finishes after reading one line, but the producer keeps running and never exits, even though it should receive a broken-pipe error on its next write. Your code never calls producer.stdout.close(). What is the cause, and what is the fix?
Show answer
The parent still holds its own copy of the pipe's read end, so the operating system sees a reader still open and never raises a broken pipe for the producer. The fix is to call producer.stdout.close() in the parent right after starting the consumer, so the consumer holds the only read end. Also call producer.wait() to collect its exit status.