【问题标题】:Setting up a pipeline using subprocess.Popen: Why close stdout but not stdin?使用 subprocess.Popen 设置管道:为什么关闭标准输出而不关闭标准输入?
【发布时间】: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 PipelineUnder what condition does a Python subprocess get a SIGPIPE?Explain example from python subprocess module)有答案指出p1.stdout 有多个阅读器,必须全部关闭以防止p1 的输出管道关闭。


p2.stdinp1.stdout之间是什么关系,是不是一定要关闭p2.stdin

【问题讨论】:

    标签: python subprocess pipe


    【解决方案1】:

    不,您不必关闭p2.stdin。事实上你不能,因为它是无。

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


    我编写了一个测试程序(Python 3),如果CLOSE_P1 = TrueBrokenPipeError 终止,但永远旋转?如果CLOSE_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')
    

    【讨论】:

      猜你喜欢
      • 2013-11-06
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-30
      相关资源
      最近更新 更多