在Python中进行冲洗时,如何防止BrokenPipeError?

在Python中进行冲洗时,如何防止BrokenPipeError?,第1张

在Python中进行冲洗时,如何防止BrokenPipeError?

BrokenPipeError
是正常现象,因为读过程(头)会终止并关闭管道的末端,而写过程(python)仍会尝试进行写 *** 作。

Is
一种异常情况,并且python脚本收到一个

BrokenPipeError
-更准确地说,Python解释器收到一个系统SIGPIPE信号,该信号捕获并引发该信号
BrokenPipeError
以允许脚本处理错误。

而且您可以有效地处理该错误,因为在上一个示例中,您仅看到一条消息,指出忽略了该异常-
好的,这不是真的,但似乎与Python中的这个开放问题有关:Python开发人员认为警告用户注意非常重要异常情况。

真正发生的是,即使您捕获到异常,Python解释器AFAIK始终会在stderr上发出信号。但是您只需要在退出前关闭stderr即可消除该消息。

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

  • 像上一个示例一样捕获错误
  • 捕获IOError(在Windows64上为Python34)或BrokenPipeError(在FreeBSD 9.0上为Python 33)-并显示一条消息
  • 在stderr上显示自定义的 “完成” 消息(由于管道断开,stdout已关闭)
  • *退出以 *关闭 消息之前 关闭stderr

这是我使用的脚本:

import systry:    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 | head -10

0123456789BrokenPipeError caughtDone

如果您不想要多余的消息,请使用:

import systry:    for i in range(4000): print(i, flush=True)except (BrokenPipeError, IOError):    passsys.stderr.close()


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5439948.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存