Explain example pipeline from Python subprocess module(解释来自 Python 子流程模块的示例管道)
问题描述
17.1.4.2:替换 shell 管道部分python subprocess 模块说要替换
Section 17.1.4.2: Replacing shell pipeline of the python subprocess module says to replace
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?什么样的关闭是不关闭的?究竟是什么,它正在关闭?
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.
推荐答案
你正在关闭 parent 进程中的 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.)
这篇关于解释来自 Python 子流程模块的示例管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:解释来自 Python 子流程模块的示例管道
基础教程推荐
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01