Created
June 5, 2026 13:19
-
-
Save apcamargo/99b2ffd8489355aa0ffb9c4d3a79944b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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