How to prevent BrokenPipeError when doing a flush in Python?

后端 未结 7 1684
没有蜡笔的小新
没有蜡笔的小新 2020-12-05 00:31

Question: Is there a way to use flush=True for the print() function without getting the BrokenPipeError?

I have a script pipe.py

7条回答
  •  伪装坚强ぢ
    2020-12-05 00:40

    While others have covered the underlying issue in great detail there is a straightforward workaround:

    python whatever.py | tail -n +1 | head -n3000
    

    Explanation: tail buffers until it's STDIN is closed (python quits and closes its STDOUT). So only tail gets the SIGPIPE when head quits. The -n +1 is effectively a no-op, making tail output the "tail" starting at line 1, which is the entire buffer.

提交回复
热议问题