gracefully handling broken pipes (was Re: Converting a string to an array?)

Tim Chase python.list at
Thu Jan 12 18:05:43 EST 2006

>  >>> import random
>  >>> s = "abcdefg"
>  >>> data = list(s)
>  >>> random.shuffle(data)
>  >>> "".join(data)
> 'bfegacd'
> fit you better?

Excellent!  Thanks.  I kept trying to find something like an 
array() function.  Too many languages, too little depth.

The program was just a short script to scramble the insides of 
words to exercise word recognition, even when the word is mangled.

It's amazing how little code it takes to get this working.

When using it as a filter, if a downstream pipe (such as "head") 
cuts it off, I get an error:

	bash# ./ bigfile.txt | head -50

	[proper output here]

	Traceback (most recent call last):
	  File "./", line 11, in ?
	    print r.sub(shuffleWord, line),
	IOError: [Errno 32] Broken pipe

At the moment, I'm just wrapping the lot in a try/except block, 
and ignoring the error.  Is there a better way to deal with this 
gracefully?  If some more serious IO error occurred, it would be 
nice to not throw that baby out with the bath-water.  Is there a 
way to discern a broken pipe from other IOError exceptions?

Thanks again.


import random, sys, re
r = re.compile("[A-Za-z][a-z]{3,}")
def shuffleWord(matchobj):
         s =
         a = list(s[1:-1])
         return "".join([s[0], "".join(a), s[-1]])
         for line in sys.stdin.readlines():
                 print r.sub(shuffleWord, line),
except IOError:

More information about the Python-list mailing list