viernes, 10 de julio de 2009

Python broken pipe

This could be little weird but I have seen this, more than once. When you work in python , parsing the standard input, and for some reason you use a pipe at the end of you process to see the head or tail like:
python foo.py| head
and you get a Broken Pipe Error then the next code snippet could be useful.


import sys
for line in sys.stdin:
print line.strip()


Then run your program and you will get

$ yes | python pipe.py |head
y
y
y
y
y
Traceback (most recent call last):
File "pipe.py", line 5, in ?
print line
IOError: [Errno 32] Broken pipe


To avoid this error just use signal package:

import signal
import sys

signal.signal(signal.SIGPIPE, signal.SIG_DFL)

for line in sys.stdin:
print line.strip()



Enjoy

1 comentario:

  1. Thanks for that code snippet. Works like a charm. Now I just need to read up about *why* it works. :-)

    ResponderEliminar