解释 Python 子流程模块中的示例管道

发布于 2024-11-08 17:08:26 字数 647 浏览 0 评论 0原文

python subprocess模块​​的17.1.4.2:替换shell管道部分说替换

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 会阻止任何输出通过管道发送吗? (显然不会,我尝试运行代码并且运行良好)。 为什么需要调用close让p1接收SIGPIPE?不关闭的是什么样的关闭呢?到底是什么关闭了?

请将此视为一个学术问题,除了更好地理解这些事情之外,我并不想完成任何事情。

Section 17.1.4.2: Replacing shell pipeline of the python subprocess module says to replace

output=`dmesg | grep hda`

with

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 comment to the third line explains why the close function is being called, but not why it makes sense. It doesn't, to me. Will not closing p1.stdout before the communicate method is called prevent any output from being sent through the pipe? (Obviously it won't, I've tried to run the code and it runs fine). Why is it necessary to call close to make p1 receive SIGPIPE? What kind of close is it that doesn't close? What, exactly, is it closing?

Please consider this an academic question, I'm not trying to accomplish anything except understanding these things better.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

隔纱相望 2024-11-15 17:08:26

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

You are closing p1.stdout in the parent process, thus leaving dmesg as the only process with that file descriptor open. If you didn't do this, even when dmesg closed its stdout, you would still have it open, and a SIGPIPE would not be generated. (The OS basically keeps a reference count, and generates SIGPIPE when it hits zero. If you don't close the file, you prevent it from ever reaching zero.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文