how to handle broken pipes

I

Igor Mikushkin

Hello all!

Could anyone please say me what is the right way to handle broken
pipes in Python?
I can wrap all my print statements with try/except blocks but it looks
like overkill for me.

I'm using my Python script this way: my_script | less
The script produces a lot of data.
So usually when I find what I'm looking for and press 'q' script is
still writing something.

Thanks in advance,
Igor
 
J

Jorgen Grahn

Hello all!

Could anyone please say me what is the right way to handle broken
pipes in Python?
I can wrap all my print statements with try/except blocks but it looks
like overkill for me.

I'm using my Python script this way: my_script | less
The script produces a lot of data.
So usually when I find what I'm looking for and press 'q' script is
still writing something.

You mean like this on Unix?

python -c 'while 1: print "hello, world"'|less

which produces

Traceback (most recent call last):
File "<string>", line 1, in <module>
IOError: [Errno 32] Broken pipe

Well, you can catch IOError, examine the errno, and do a sys.exit()
if it's EPIPE. Don't know if it should be sys.exit(0) or sys.exit(1)
though.

Oh, and *now* I see what you wrote at the top:
I can wrap all my print statements with try/except blocks but it looks
like overkill for me.

It's overkill if you have to do it for each print. You should always
(IMHO) wrap all your logic inside an object or a function, let's say
foo(). Then you only have to wrap the single call to foo().

There should be an even cleaner way. Mine is kind of ugly (catch,
examine, exit or re-raise) and it also incorrectly catches broken pipes
which aren't related to sys.stdout/stderr.

There is a similar problem with Ctrl-C, by the way -- the user gets a
KeyboardInterrupt exception thrown in his face where other languages
would have exited silently by default.

/Jorgen
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top