【问题标题】:Explain example pipeline from Python subprocess module解释来自 Python 子流程模块的示例管道
【发布时间】:2011-08-28 03:43:01
【问题描述】:

python子进程模块的17.1.4.2: 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]

第三行的注释解释了为什么调用 close 函数,但没有解释为什么它有意义。对我来说不是。在调用通信方法之前不关闭 p1.stdout 会阻止 any 输出通过管道发送吗? (显然不会,我尝试运行代码并且运行良好)。 为什么需要调用close来让p1接收SIGPIPE?什么样的关闭是不关闭的?究竟是什么,它正在关闭?

请考虑这是一个学术问题,除了更好地理解这些事情之外,我并没有试图完成任何事情。

【问题讨论】:

  • stdin 和 stdout 是文件。所以你应该关闭它们以释放管道。

标签: python subprocess


【解决方案1】:

您正在关闭 parent 进程中的p1.stdout,从而使 dmesg 作为打开该文件描述符的唯一进程。如果您不这样做,即使 dmesg 关闭了它的标准输出,您仍然会打开它,并且不会生成 SIGPIPE。 (操作系统基本上保持一个引用计数,并在它达到零时生成SIGPIPE。如果你不关闭文件,你会阻止它达到零。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 2014-05-29
    • 2018-04-25
    • 1970-01-01
    相关资源
    最近更新 更多