gpt4 book ai didi

Python 子进程读取进程在写入进程示例之前终止,需要说明

转载 作者:太空宇宙 更新时间:2023-11-04 01:24:25 25 4
gpt4 key购买 nike

代码片段来自:http://docs.python.org/3/library/subprocess.html#replacing-shell-pipeline

output=`dmesg | grep hda`
# becomes
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]

问题:我不太明白为什么需要这一行:p1.stdout.close()?如果通过这样做 p1 stdout 甚至在它完全完成输出数据并且 p2 仍然存在之前就关闭了怎么办?我们这么快关闭 p1.stdout 不是在冒这个风险吗?这是如何工作的?

最佳答案

p1.stdout.close() 关闭文件描述符的 Python 副本p2 已经打开了该描述符(通过 stdin=p1.stdout),因此关闭 Python 的描述符不会影响 p2。然而,现在管道末端只打开一次,所以当它关闭时(例如,如果 p2 死了),p1 将看到管道关闭并得到 SIGPIPE.

如果你没有在 Python 中关闭 p1.stdout,并且 p2 死了,p1 将不会得到任何信号,因为 Python 的描述符将是保持管道打开。

关于Python 子进程读取进程在写入进程示例之前终止,需要说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18973038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com