BrokenPipeError: Broken Pipe

BrokenPipeError: [Errno 32] Broken pipe

Quick Answer

The receiving end of a pipe was closed while you were writing. This commonly happens when piping Python output to head or grep and the reader closes early. Handle the signal or catch the error.

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 closes

The 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. 1

    Handle BrokenPipeError

    Wrap output in try/except BrokenPipeError.

  2. 2

    Reset SIGPIPE

    Use signal.signal(signal.SIGPIPE, signal.SIG_DFL).

  3. 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