Why This Happens
When you pipe output (python script.py | head -5), head closes the pipe after reading enough lines. Further writes to stdout raise BrokenPipeError. This is normal behavior.
The Problem
# python script.py | head -5
for i in range(1000000):
print(i) # BrokenPipeError when head closesThe Fix
import sys
import signal
# Ignore SIGPIPE:
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
# Or handle the error:
try:
for i in range(1000000):
print(i)
except BrokenPipeError:
sys.stderr.close()
sys.exit(0)Step-by-Step Fix
- 1
Handle BrokenPipeError
Wrap output in try/except BrokenPipeError.
- 2
Reset SIGPIPE
Use signal.signal(signal.SIGPIPE, signal.SIG_DFL).
- 3
Flush output
Use sys.stdout.flush() after critical writes.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free