There is a known issue in Python, where \"close failed in file object destructor\" when \"Broken pipe\" happens on stdout - Python tracker Issue 11380; also seen in python - Why
This is a VERY ugly hack to suppress the error message from being shown in case printing to stdout caused a broken pipe (e.g. because a pager process invoked like your-program.py | less
was quit without scrolling to the bottom of the output:
try:
actual_code()
except BrokenPipeError:
sys.stdout = os.fdopen(1)