【发布时间】:2018-08-28 08:05:07
【问题描述】:
subprocess.popen (1) 的 Python 3 文档提供了以下管道示例代码:
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]
启动 p2 后的 p1.stdout.close() 调用很重要,以便在 p2 在 p1 之前退出时 p1 接收 SIGPIPE。
为什么这是必要的?之前的问题(Replacing Shell Pipeline、Under what condition does a Python subprocess get a SIGPIPE?、Explain example from python subprocess module)有答案指出p1.stdout 有多个阅读器,必须全部关闭以防止p1 的输出管道关闭。
p2.stdin和p1.stdout之间是什么关系,是不是一定要关闭p2.stdin?
【问题讨论】:
标签: python subprocess pipe