相关疑难解决方法(0)

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

问题:有没有办法使用flush=Trueprint()功能而无法获得BrokenPipeError

我有一个脚本pipe.py:

for i in range(4000):
    print(i)
Run Code Online (Sandbox Code Playgroud)

我从Unix命令行这样称呼它:

python3 pipe.py | head -n3000
Run Code Online (Sandbox Code Playgroud)

它返回:

0
1
2
Run Code Online (Sandbox Code Playgroud)

这个脚本也是如此:

import sys
for i in range(4000):
    print(i)
    sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)

但是,当我运行此脚本并将其传递给head -n3000:

for i in range(4000):
    print(i, flush=True)
Run Code Online (Sandbox Code Playgroud)

然后我收到这个错误:

    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
Run Code Online (Sandbox Code Playgroud)

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

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

python unix flush broken-pipe python-3.x

26
推荐指数
3
解决办法
2万
查看次数

标签 统计

broken-pipe ×1

flush ×1

python ×1

python-3.x ×1

unix ×1