- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
问题:有没有办法在 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 即可摆脱该消息。
我将您的脚本稍微更改为:
这是我使用的脚本:
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/
我编写了一个脚本来帮助我处理数据库。具体来说,我正在尝试处理磁盘上的文件并将这项工作的结果添加到我的数据库中。我复制了下面的代码,但删除了大部分与我的数据库无关的逻辑,以尽量使这个问题更广泛和有用。
我已将我的代码归结为以下内容: from selenium import webdriver from time import sleep b = webdriver.Firefox() sleep(
我正在学习多处理,并且在使用队列时遇到这个问题之前一直没有遇到任何问题。本质上,队列被填满,但随后似乎出了问题并且崩溃了。 我在 Windows 10 上运行 python 3.6.8。当我不使用队列
问题:有没有办法在 print() 函数中使用 flush=True 而不会得到 BrokenPipeError ? 我有一个脚本pipe.py: for i in range(4000):
我有一个 Python 3.7.4 脚本,使用多处理和线程来抓取 API。它使用 GET 请求来获取主题标签的统计信息,然后在该页面上收集更多主题标签以添加到从 API 中抓取的列表中。它会工作几分钟
在执行以下代码时尝试抓取网站的索引页面,并尝试识别包含登录文本的元素,如下所示: from selenium import webdriver import os chromedriver = "/u
考虑这个 Python 脚本: for i in range(4000): print(i) 和这个 Perl 脚本: for my $i (0..4000-1) { print $i
我在 App Engine Standard 上有一个使用 Cloud SQL (postgres) 数据库的应用。每当应用程序似乎闲置时,我都会收到 BrokenPipeError s,但我不明白为
对于我的代码部分,您可以在下面找到,有时我会在标题中得到错误。它可能与大量数据或互联网连接不良有关吗?我尝试使用 gspread 从一个 google 电子表格到另一个 14k 行。 有什么办法可以避
大家好!我在 PyPI 有一个 python 包,我去更新一下。但上传命令没有正确执行! 命令: twine upload dist/* 错误: ConnectionError: ('Connecti
我正在尝试执行名为 "Training a classifier" 的教程使用 PyTorch。 当尝试调试这部分代码时: import matplotlib.pyplot as plt import
嗨,我制作了运行良好的模型服务器客户端,我还创建了单独的 GUI,需要两个输入 server IP and port它只检查是否 server起来与否。但是当我运行服务器然后运行我的 GUI 并输入服
我是一名优秀的程序员,十分优秀!