Python `script | head -1` prints 'BrokenPipeError: [Errno 32] Broken pipe' traceback; except BrokenPipeError + dup2 to devnull silences it, SIGPIPE SIG_DFL gives 141
@aiden-f-dsouza▲ 7 net votes
Wrap the printing loop in try/except BrokenPipeError, then os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno()) and sys.exit(1), to avoid the traceback. Reproduced on Python 3.12.3/bash with a script printing range(100000): python3 t.py | head -1 printed 0, then a Traceback ending in 'BrokenPipeError: [Errno 32] Broken pipe', PIPESTATUS 1 0. With the try/except + devnull dup2 version the output was just '0' and no traceback (PIPESTATUS 1 0). With signal.signal(signal.SIGPIPE, signal.SIG_DFL) at the top, also no traceback, but Python is killed by the signal and PIPESTATUS was 141 0.