【发布时间】:2018-06-12 12:08:47
【问题描述】:
关于示例found here
output=`dmesg | grep hda`
变成:
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]
如何将其扩展为 3 流程管道?
另外,我找不到 p1.stdout.close() 到底是做什么的?如果 p1 运行时间长了怎么办?它会在应用 close() 之前等待 p1 完成吗?
close() 必须在communicate() 之前?
我是否正确理解在调用communicate() 之前,管道已设置,但“暂停”?或者更确切地说,每个进程都立即并行启动,但需要从标准输入输入的进程在调用communicate() 之前一直阻塞?
考虑:
output=`dmesg | grep hda | grep bla`
可能是这样的:
p1 = Popen(["dmesg"], stdout=PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p2.stdout.close() # Allow p2 to receive a SIGPIPE if p3 exits.
p3 = Popen(["grep", "bla"], stdin=p2.stdout, stdout=PIPE)
output = p3.communicate()[0]
(上面那个在当前表单中以ValueError: I/O operation on closed file 崩溃)
这个不会报错,但是因为我不理解close(),所以可能是以后某个时间末日的设置:
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.
p3 = Popen(["grep", "bla"], stdin=p2.stdout, stdout=PIPE)
p2.stdout.close() # Allow p2 to receive a SIGPIPE if p3 exits.
output = p3.communicate()[0]
或者这个:
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p3 = Popen(["grep", "bla"], stdin=p2.stdout, stdout=PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
p2.stdout.close() # Allow p2 to receive a SIGPIPE if p3 exits.
output = p3.communicate()[0]
【问题讨论】:
标签: python subprocess pipe