Created
March 28, 2019 17:43
-
-
Save noahp/8fc6e5239a6358ce43bd3b8af19bacba to your computer and use it in GitHub Desktop.
Decorator for broken pipe error when paging python script output
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
""" | |
Python when printing to a pager (less), if you exit without | |
reading all the output, you get an ugly but harmless exception: | |
BrokenPipeError: [Errno 32] Broken pipe | |
If you try to just trap the error, you still get this print | |
on python3: | |
Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> | |
BrokenPipeError: [Errno 32] Broken pipe | |
Found an answer on stackoverflow that gets us close, put all together | |
you can use this: | |
""" | |
# https://stackoverflow.com/a/35761190 | |
def suppress_broken_pipe_msg(f): | |
@wraps(f) | |
def wrapper(*args, **kwargs): | |
try: | |
broken_pipe_exception = BrokenPipeError | |
except NameError: # Python 2 | |
broken_pipe_exception = IOError | |
try: | |
return f(*args, **kwargs) | |
except SystemExit: | |
raise | |
except broken_pipe_exception as exc: | |
if broken_pipe_exception == IOError: | |
if exc.errno != EPIPE: | |
raise | |
except: | |
print_exc() | |
exit(1) | |
finally: | |
try: | |
stdout.flush() | |
finally: | |
try: | |
stdout.close() | |
finally: | |
try: | |
stderr.flush() | |
finally: | |
stderr.close() | |
return wrapper | |
@suppress_broken_pipe_msg | |
def main(): | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment