File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change @@ -503,3 +503,37 @@ be sent, and the handler raises an exception. ::
503503
504504 signal.alarm(0) # Disable the alarm
505505
506+ Note on SIGPIPE
507+ ---------------
508+
509+ Piping output of your program to tools like :manpage: `head(1)` will
510+ cause a :const: `SIGPIPE ` signal to be sent to your process when the receiver
511+ of its standard output closes early. This results in an exception
512+ like :code: `BrokenPipeError: [Errno 32] Broken pipe `. To handle this
513+ case, wrap your entry point to catch this exception as follows::
514+
515+ import os
516+ import sys
517+
518+ def main():
519+ try:
520+ # simulate large output (your code replaces this loop)
521+ for x in range(10000):
522+ print("y")
523+ # flush output here to force SIGPIPE to be triggered
524+ # while inside this try block.
525+ sys.stdout.flush()
526+ except BrokenPipeError:
527+ # Python flushes standard streams on exit; redirect remaining output
528+ # to devnull to avoid another BrokenPipeError at shutdown
529+ devnull = os.open(os.devnull, os.O_WRONLY)
530+ os.dup2(devnull, sys.stdout.fileno())
531+ sys.exit(1) # Python exits with error code 1 on EPIPE
532+
533+ if __name__ == '__main__':
534+ main()
535+
536+ Do not set :const: `SIGPIPE `'s disposition to :const: `SIG_DFL `
537+ in order to avoid :exc: `BrokenPipeError `. Doing that would cause
538+ your program to exit unexpectedly also whenever any socket connection
539+ is interrupted while your program is still writing to it.
You can’t perform that action at this time.
0 commit comments