BrokenPipeError: What It Means and How to Fix It
Error reference
BrokenPipeError
Language
Severity
LowWhen it happens
BrokenPipeError is raised when a process tries to write to a pipe whose reading end has been closed.
Potential fixes
Catch BrokenPipeError around your write operations and exit cleanly. For scripts that write to stdout, closing sys.stderr before exit suppresses the noisy traceback. This is expected behavior in Unix pipelines and is usually not a bug in your code.
Related errors
Deep dive
BrokenPipeError is raised when a process tries to write to a pipe whose reading end has been closed. It commonly occurs in Unix pipelines when a downstream command (like head or grep) finishes and closes its stdin before the upstream process is done writing.
Why it happens
- •Piping output to a command that exits early (e.g. head -1 or less).
- •A network socket is written to after the remote end has closed the connection.
- •A subprocess reading from a pipe exits before consuming all output.
Potential fixes
Catch BrokenPipeError around your write operations and exit cleanly. For scripts that write to stdout, closing sys.stderr before exit suppresses the noisy traceback. This is expected behavior in Unix pipelines and is usually not a bug in your code.
Examples
Code that triggers the error
# python script.py | head -1
import sys
for i in range(1000):
print(i) # BrokenPipeError after head closes the pipeError output
BrokenPipeError: [Errno 32] Broken pipe
Fixed code
import sys
try:
for i in range(1000):
print(i)
except BrokenPipeError:
# Reader closed early, that is fine
sys.stderr.close()Practice in English
How would you explain a BrokenPipeError to a fellow dev? Choose the right phrase:
"I hit an error...
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free