代码之家  ›  专栏  ›  技术社区  ›  b0fh

当启动顺序更改时,运行管道化子流程会产生不同的结果?

  •  1
  • b0fh  · 技术社区  · 15 年前

    我正在运行python3程序中的命令管道,使用 subprocess.* 我不想要 我把论点传给我的小组委员会,确保这些论点不会被壳牌曲解,这简直是噩梦。

    这个 subprocess Doc给出了如何执行此操作的示例:

    p1 = Popen(command1, stdout=PIPE)
    p2 = Popen(command2, stdin=p1.stdout)
    p2.wait()
    p1.wait()
    

    这很管用。但是,我想知道在生产商之前启动消费者是否更安全,所以

    p2 = Popen(command2, stdin=PIPE)
    p1 = Popen(command1, stdout=p2.stdin)
    p2.wait()
    p1.wait()
    

    我原以为这一切都会以同样的方式发生,但显然不是这样。第一个代码工作得很完美;第二个代码,我的程序挂起;如果我看系统,我可以看到p1死了,等待收获,p2永远挂起。对此有合理的解释吗?

    1 回复  |  直到 13 年前
        1
  •  1
  •   Constantin    15 年前

    看起来p2(消费者)挂起是因为 stdin 保持开放状态。如果这样修改代码,则两个进程都将成功完成:

    p2 = Popen(command2, stdin=PIPE)
    p1 = Popen(command1, stdout=p2.stdin)
    p1.wait()
    p2.stdin.close()
    p2.wait()
    

    我敢打赌这就是行为中的泄漏抽象法则。