From a404aabada03995a9ee66b8eff04bb7b258c3450 Mon Sep 17 00:00:00 2001 From: Johann Dreo Date: Mon, 2 Sep 2013 17:16:14 +0200 Subject: [PATCH] Silently handle broken pipes Two errors could occur when using a command that break the pipe on which colout is supposed to write, like head or tail: ls | colout . red | head -n 1 This fix set the SIGPIPE handler to kill the program instead of ending in a write error when a broken pipe occurs and silently handle broken pipes IOError exceptions. --- colout/colout.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/colout/colout.py b/colout/colout.py index d0dffcd..70e4b16 100755 --- a/colout/colout.py +++ b/colout/colout.py @@ -13,6 +13,12 @@ import glob import math import importlib import logging +import signal + +# set the SIGPIPE handler to kill the program instead of +# ending in a write error when a broken pipe occurs +signal.signal( signal.SIGPIPE, signal.SIG_DFL ) + ############################################################################### # Ressource parsing helpers @@ -524,8 +530,16 @@ def write(colored, stream = sys.stdout): """ Write "colored" on sys.stdout, then flush. """ - stream.write(colored) - stream.flush() + try: + stream.write(colored) + stream.flush() + + # Silently handle broken pipes + except IOError: + try: + stream.close() + except IOError: + pass def map_write( stream_in, stream_out, function, *args ):