Skip to content

Instantly share code, notes, and snippets.

@apcamargo
Created June 5, 2026 13:19
Show Gist options
  • Select an option

  • Save apcamargo/99b2ffd8489355aa0ffb9c4d3a79944b to your computer and use it in GitHub Desktop.

Select an option

Save apcamargo/99b2ffd8489355aa0ffb9c4d3a79944b to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# https://adamj.eu/tech/2025/07/20/python-fix-brokenpipeerror/
import os
import sys
from contextlib import contextmanager
from typing import Generator
@contextmanager
def handle_broken_pipe() -> Generator[None]:
"""
Prevent BrokenPipeError when the output stream is closed early, such as
when piping to head.
"""
try:
yield
sys.stdout.flush()
except BrokenPipeError:
# Python flushes standard streams on exit; redirect remaining output
# to devnull to avoid another BrokenPipeError at shutdown
devnull = os.open(os.devnull, os.O_WRONLY)
os.dup2(devnull, sys.stdout.fileno())
with handle_broken_pipe():
for i in range(1_000):
print(f"This is line {i}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment