Sub topic 13
Building a pipeline between two processes
This chapter assumes you know subprocess.run, the basics of Popen (including communicate), and that every process has standard input, output and error streams. A pipeline connects the output of one process to the input of another, as the shell does with producer | consumer.
The idea
When you use subprocess.run with capture_output=True, the output returns to Python and you would have to pass it on yourself. In a pipeline, the operating system connects the two processes directly. Python only starts them and collects the final result.
A working pipeline
The example below runs a producer that prints a b c. A consumer counts the words it reads from standard input.
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())It prints 3.
How it works
- The producer is started with
stdout=subprocess.PIPE. Python creates an operating system pipe and exposes the read end asproducer.stdout. - The consumer receives that read end as
stdin=producer.stdout. The child reads from it directly. producer.stdout.close()closes the parent's copy of the read end. The consumer keeps its own copy.consumer.communicate()reads the consumer's output and waits for it to exit.producer.wait()collects the producer's exit status so it does not remain a zombie process.
Common errors
The most common mistake is leaving out producer.stdout.close(). The code often still works, so the omission is easy to miss. The reasons to include it are:
- The close matters most for the producer. If the consumer exits early, the producer should receive a broken pipe signal and stop. While the parent holds its own copy of the read end, that signal may never arrive, and the producer can block or keep running.
- It also follows the pattern in the Python documentation, so readers will recognize it.
Other points to watch:
- Only the last process is captured. The producer's
stdoutbelongs to the consumer, so the parent cannot read it. If you need the intermediate output, use tworuncalls or a different design. - Exit codes are separate. Shell pipelines usually report only the last command's status. With
Popenyou can checkproducer.returncodeandconsumer.returncodeafter both have finished. - Do not call
communicate()on the producer when its output is piped to the consumer. That would make the parent consume the data the consumer needs. - Stderr is not piped. Each process still writes errors to the parent's stderr unless you set
stderrexplicitly.
Checking both exit codes
A failed producer can leave the consumer with empty input, and the consumer may still succeed. Check both processes:
import subprocess
import sys
producer = subprocess.Popen(
[sys.executable, "-c", "import sys; print('x y'); sys.exit(2)"],
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("words:", output.strip())
print("codes:", producer.returncode, consumer.returncode)This prints words: 2 and codes: 2 0. The consumer finished cleanly, but the producer failed, so the result should not be trusted.
Exercise
In a two-process pipeline built with Popen, why do you call producer.stdout.close() in the parent after starting the consumer, and why must you check both return codes?
Show answer
The parent's copy of the pipe's read end must be closed so that the producer receives a broken pipe signal if the consumer exits early, and the parent does not hold the pipe open unnecessarily. Each process has its own exit status, and a consumer can succeed even when the producer failed, so both returncode values must be checked to detect a failed pipeline.