How to prevent BrokenPipeError when doing a flush in Python?

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

    A note on SIGPIPE was added in Python 3.7 documentation, and it recommends to catch BrokenPipeError this way:

    import os
    import sys
    
    def main():
        try:
            # simulate large output (your code replaces this loop)
            for x in range(10000):
                print("y")
            # flush output here to force SIGPIPE to be triggered
            # while inside this try block.
            sys.stdout.flush()
        except BrokenPipeError:
            # Python flushes standard streams on exit; redirect remaining output
            # to devnull to avoid another BrokenPipeError at shutdown
            devnull = os.open(os.devnull, os.O_WRONLY)
            os.dup2(devnull, sys.stdout.fileno())
            sys.exit(1)  # Python exits with error code 1 on EPIPE
    
    if __name__ == '__main__':
        main()
    

    Importantly, it says:

    Do not set SIGPIPE’s disposition to SIG_DFL in order to avoid BrokenPipeError. Doing that would cause your program to exit unexpectedly also whenever any socket connection is interrupted while your program is still writing to it.

提交回复
热议问题