The Python 3 documentation for subprocess.popen
(1) presents the following sample code for pipelines:
from subprocess import Popen, PIPE
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
The p1.stdout.close() call after starting the p2 is important in order for p1 to receive a SIGPIPE if p2 exits before p1.
Why is this necessary? Previous questions (Replacing Shell Pipeline, Under what condition does a Python subprocess get a SIGPIPE?, Explain example from python subprocess module) have answers stating that p1.stdout
has multiple readers, which must all be closed to prevent p1
's output pipe from closing.
What is the relation between p2.stdin
and p1.stdout
, and do I have to close p2.stdin
?