python - 关闭管道 python 子进程的标准输出

标签 python shell subprocess pipeline

这是我在 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.

我真的不明白为什么我们必须在创建 p2 后关闭 p1.stdout。 p1.stdout.close() 什么时候执行? 当 p2 永远不会结束时会发生什么? 当 nor p1 或 p2 结束时会发生什么?

最佳答案

来自 Wikipedia , SIGPIPE 是当进程试图写入管道而另一端没有进程连接时发送给进程的信号。

当您第一次创建 p1 时使用 stdout=PIPE ,有一个进程连接到管道,这是你的 Python 进程,你可以使用 p1.stdout 读取输出。 .

当您创建 p2 时使用 stdin=p1.stdout现在有两个进程连接到管道 p1.stdout .

通常,当您在管道中运行进程时,您希望所有进程在任何进程结束时结束。为了自动发生这种情况,您需要关闭 p1.stdout所以p2.stdin是附加到该管道的唯一进程,如果 p2结束和p1将附加数据写入标准输出,它将收到 SIGPIPE,因为不再有任何进程附加到该管道。

关于python - 关闭管道 python 子进程的标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7391689/

相关文章:

Python 日志模块输出到屏幕延迟

python - 在 YouTube 上搜索并返回 Python 中的所有链接

python - 如何在Python中使用pyqt创建饼图

bash - 使用 Golang 运行 Grep 命令时退出状态 2

linux - 在 Linux 服务器上将 Excel 提取为文本

python - 波浪号 (~) 在 subprocess.Popen() 中不起作用

python - PyQt : How to set up a widget hidding an other widget if it's visible?

c - 该命令在 C 中有效吗?

python - 如何通过 Python 子进程杀死 omxplayer

python - Python 中的线程子进程