OSPython Error

BrokenPipeError

BrokenPipeError: [Errno 32] Broken pipe

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print(i)  # BrokenPipeError when head closes
BrokenPipeError: [Errno 32] Broken pipe

What causes this error

An attempt was made to write to a pipe or socket whose other end has been closed. The reader disconnected before the writer finished.

How to fix it

Catch BrokenPipeError and handle it gracefully. For CLI tools, consider setting `signal.signal(signal.SIGPIPE, signal.SIG_DFL)`. In servers, log the disconnection and clean up resources.

Code that causes this error

Broken
# Running: python script.py | head -1
import sys
for i in range(10000):
    print(i)  # BrokenPipeError when head closes

Fixed code

Fixed
import sys
import signal

signal.signal(signal.SIGPIPE, signal.SIG_DFL)
for i in range(10000):
    try:
        print(i)
    except BrokenPipeError:
        sys.exit(0)

About BrokenPipeError

BrokenPipeError is raised when writing to a pipe or socket whose reading end has been closed. This is a subclass of ConnectionError and corresponds to the POSIX errno EPIPE. The classic scenario is a command-line tool piped to `head` — when head has read enough lines and closes its stdin, the writing process receives SIGPIPE (or BrokenPipeError in Python).

It also occurs in client-server communication when the client disconnects before the server finishes sending data. In web applications, this often happens when a user navigates away before the response is fully sent. The error is usually benign and can be safely ignored in many cases, though you should ensure any necessary cleanup still occurs.

For command-line tools, Python provides `signal.signal(signal.SIGPIPE, signal.SIG_DFL)` to restore the default behavior of silently terminating on broken pipes.

Common scenarios

1

Running scripts without sufficient file system permissions

2

Connecting to servers that are not running or are unreachable

3

Installing Python packages without proper environment setup

4

Running out of disk space or file descriptors during I/O operations

Related errors