On Wed, 2009-10-14, Igor Mikushkin wrote: > 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 -- // Jorgen Grahn <grahn@ Oo o. . . \X/ snipabacken.se> O o . -- http://mail.python.org/mailman/listinfo/python-list