gpt4 book ai didi

python - 在 Python 中进行刷新时如何防止 BrokenPipeError?

转载 作者:IT老高 更新时间:2023-10-28 20:27:49 25 4
gpt4 key购买 nike

问题:有没有办法在 print() 函数中使用 flush=True 而不会得到 BrokenPipeError ?

我有一个脚本pipe.py:

for i in range(4000):
print(i)

我在 Unix 命令行中这样调用它:

python3 pipe.py | head -n3000

然后它返回:

0
1
2

这个脚本也是如此:

import sys
for i in range(4000):
print(i)
sys.stdout.flush()

但是,当我运行此脚本并将其通过管道传输到 head -n3000 时:

for i in range(4000):
print(i, flush=True)

然后我得到这个错误:

    print(i, flush=True)
BrokenPipeError: [Errno 32] Broken pipe
Exception BrokenPipeError: BrokenPipeError(32, 'Broken pipe') in <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> ignored

我也尝试了下面的解决方案,但我仍然得到 BrokenPipeError:

import sys
for i in range(4000):
try:
print(i, flush=True)
except BrokenPipeError:
sys.exit()

最佳答案

BrokenPipeError 是正常的,因为读取进程(head)终止并关闭其管道末端,而写入进程(python)仍在尝试写入。

is 是异常情况,python 脚本接收到 BrokenPipeError - 更准确地说,Python 解释器接收到它捕获的系统 SIGPIPE 信号并引发 BrokenPipeError 允许脚本处理错误。

您可以有效地处理错误,因为在上一个示例中,您只看到一条消息说异常被忽略 - 好吧,这不是真的,但似乎与 open issue 有关在 Python 中:Python 开发人员认为警告用户异常情况很重要。

真正发生的是 AFAIK,python 解释器总是在 stderr 上发出信号,即使你捕获了异常。但是您只需要在退出之前关闭 stderr 即可摆脱该消息。

我将您的脚本稍微更改为:

  • 像在上一个示例中那样捕获错误
  • 捕获 IOError(我在 Windows64 上的 Python34 中得到)或 BrokenPipeError(在 FreeBSD 9.0 上的 Python 33 中) - 并为此显示一条消息
  • 在 stderr 上显示自定义 Done 消息(stdout 由于管道损坏而关闭)
  • 关闭 stderr,然后再退出以删除消息

这是我使用的脚本:

import sys

try:
for i in range(4000):
print(i, flush=True)
except (BrokenPipeError, IOError):
print ('BrokenPipeError caught', file = sys.stderr)

print ('Done', file=sys.stderr)
sys.stderr.close()

这里是 python3.3 pipe.py | 的结果头 -10 :

0
1
2
3
4
5
6
7
8
9
BrokenPipeError caught
Done

如果您不想看到无关消息,请使用:

import sys

try:
for i in range(4000):
print(i, flush=True)
except (BrokenPipeError, IOError):
pass

sys.stderr.close()

关于python - 在 Python 中进行刷新时如何防止 BrokenPipeError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26692284/

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