How to prevent BrokenPipeError when doing a flush in Python?

后端 未结 7 1682
没有蜡笔的小新
没有蜡笔的小新 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 01:04

    Ignore SIGPPIE temporarily

    I'm not sure how bad an idea this is, but it works:

    #!/usr/bin/env python3
    
    import signal
    import sys
    
    sigpipe_old = signal.getsignal(signal.SIGPIPE)
    signal.signal(signal.SIGPIPE, signal.SIG_DFL)
    for i in range(4000):
        print(i, flush=True)
    signal.signal(signal.SIGPIPE, sigpipe_old)
    
    0 讨论(0)
提交回复
热议问题