Lingua-e
Python

What is a BrokenPipeError?

← Errors

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.

Examples

Python

Code that triggers the error

# python script.py | head -1
import sys
for i in range(1000):
    print(i)  # BrokenPipeError after head closes the pipe

Error output

BrokenPipeError: [Errno 32] Broken pipe

How to fix it

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.

Fixed code

import sys

try:
    for i in range(1000):
        print(i)
except BrokenPipeError:
    # Reader closed early, that is fine
    sys.stderr.close()

Related errors

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