代码片段来自:http://docs.python.org/3/library/subprocess.html#replacing-shell-pipeline
output=`dmesg | grep hda`
# becomes
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]
问题:我不太明白为什么需要这一行:p1.stdout.close()
?
如果通过执行此操作,p1 stdout 在完全完成数据输出并且 p2 仍然存在之前就关闭了怎么办?我们这么快就关闭 p1.stdout
难道不会冒这个风险吗?这是如何工作的?
最佳答案
p1.stdout.close()
关闭 Python 的文件描述符的副本。 p2
已经打开了该描述符(通过 stdin=p1.stdout
),因此关闭 Python 的描述符不会影响 p2
。但是,现在管道末端仅打开一次,因此当它关闭时(例如,如果 p2
死亡),p1
将看到管道关闭并会收到 SIGPIPE
.
如果您没有在 Python 中关闭 p1.stdout
,并且 p2
死亡,p1
将不会收到信号,因为 Python 的描述符将是保持管道打开。
关于Python子进程读取进程在写入进程示例之前终止,需要澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18973038/