Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/facebook/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用subprocess.Popen设置管道:为什么关闭stdout而不关闭stdin?_Python_Subprocess_Pipe - Fatal编程技术网

Python 使用subprocess.Popen设置管道:为什么关闭stdout而不关闭stdin?

Python 使用subprocess.Popen设置管道:为什么关闭stdout而不关闭stdin?,python,subprocess,pipe,Python,Subprocess,Pipe,subprocess.popen()的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.com

subprocess.popen
()的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之前退出,则启动p2后的p1.stdout.close()调用对于p1接收SIGPIPE非常重要

为什么这是必要的?前面的问题(,)的答案说明
p1.stdout
有多个读卡器,这些读卡器都必须关闭,以防止
p1
的输出管道关闭



p2.stdin
p1.stdout
之间有什么关系,我是否必须关闭
p2.stdin

不,您不必关闭
p2.stdin
。事实上你不能,因为没有

这是因为
stdin=p1.stdout
,而只有当
stdin=subprocess.PIPE
时才会创建Python流对象。(见)


我编写了一个测试程序(Python3),如果
CLOSE\u P1=True
,它将以
BrokenPipeError
终止,但会永远旋转??如果
关闭\u P1=False

from subprocess import Popen, PIPE


CLOSE_P1 = True


p1 = Popen("ffmpeg "
           "-f rawvideo -pixel_format rgb24 -video_size 1x1 -i - "
           "-c copy -f rawvideo -".split(), stdin=PIPE, stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
assert p2.stdin is None

if CLOSE_P1:
    p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
p2.terminate()
while 1:
    p1.stdin.write(b'fsdafhdsf9jd9s8ha0')