[英]closing stdout of piped python subprocess
Here is what I can read in the python subprocess module documentation: 以下是我在python子进程模块文档中可以阅读的内容:
Replacing shell pipeline
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]
The p1.stdout.close() call after starting the p2 is important in order for p1
to receive a SIGPIPE if p2 exits before p1.
I don't really understand why we have to close p1.stdout after have created p2. 我真的不明白为什么在创建p2之后我们必须关闭p1.stdout。 When is exactly executed the p1.stdout.close()? 什么时候完全执行p1.stdout.close()? What happens when p2 never ends? 当p2永远不会结束时会发生什么? What happens when nor p1 or p2 end? 当p1或p2结束时会发生什么?
From Wikipedia , SIGPIPE is the signal sent to a process when it attempts to write to a pipe without a process connected to the other end. 在Wikipedia中 , SIGPIPE是在尝试写入管道而没有连接到另一端的进程时发送给进程的信号。
When you first create p1
using stdout=PIPE
, there is one process connected to the pipe, which is your Python process, and you can read the output using p1.stdout
. 当您首次使用stdout=PIPE
创建p1
,有一个进程连接到管道,这是您的Python进程,您可以使用p1.stdout
读取输出。
When you create p2
using stdin=p1.stdout
there are now two processes connected to the pipe p1.stdout
. 使用stdin=p1.stdout
创建p2
,现在有两个进程连接到管道p1.stdout
。
Generally when you are running processes in a pipeline you want all processes to end when any of the processes end. 通常,当您在管道中运行进程时,您希望所有进程在任何进程结束时结束。 For this to happen automatically you need to close p1.stdout
so p2.stdin
is the only process attached to that pipe, this way if p2
ends and p1
writes additional data to stdout, it will receive a SIGPIPE since there are no longer any processes attached to that pipe. 为了自动执行此操作,您需要关闭p1.stdout
因此p2.stdin
是附加到该管道的唯一进程,这样如果p2
结束并且p1
将其他数据写入stdout,它将收到一个SIGPIPE,因为不再有任何进程附在那根烟斗上。
OK I see. 好的我明白了。 p1.stdout is closed from my python script but remains open in p2, and then p1 and p2 communicate together. p1.stdout从我的python脚本关闭但在p2中保持打开状态,然后p1和p2一起通信。 Except if p2 is already closed, then p1 receives a SIGPIPE. 除非p2已经关闭,否则p1会收到一个SIGPIPE。 Am I correct? 我对么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.