How to swallow traceback message

Peter Otten __peter__ at web.de
Wed Aug 11 14:26:49 EDT 2010


Back9 wrote:

> I run my py app to display a file's contents, and it is normally very
> long.
> So I use it like below:
> 
> python myapp.py input_file | more
> to see them step by step.
> 
> But when I try to exit it, normally I use Ctrl+ C key to quit it.
> Problem is every time I do like it, it shows Traceback message and it
> makes my app not professional.
> 
> How do I handle it gracefully.

Step 1, provoke the error:

$ python -c"while 1: print 42" | head -n1
42
Traceback (most recent call last):
  File "<string>", line 1, in <module>
IOError: [Errno 32] Broken pipe

Step 1a, read the error message carefully ;)

Step 2, catch the error:

$ python -c"try:
    while 1: print 42
except IOError as e:
    if e.errno != 32: raise
" | head -n1
42

Step 3, repeat if necessary. IOError is only one example.

Peter



More information about the Python-list mailing list