From: Tim Harig on 11 Aug 2010 14:06 On 2010-08-11, Back9 <backgoodoo(a)gmail.com> wrote: > On Aug 11, 11:19�am, Tim Harig <user...(a)ilthio.net> wrote: >> On 2010-08-11, Back9 <backgoo...(a)gmail.com> wrote: >> > 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. >> >> You have three options. >> >> � � � � 1. Exit more properly. >> >> � � � � 2. Catch and handle SIGINT yourself. >> >> � � � � 3. Wrap whatever section of your program is being interrupted in >> � � � � � � � � try/except to catch the KeyboardInterrupt exception when it >> � � � � � � � � is generated. > > I should have mentioned that I already use try/except > KeyboardInterrupt statement. > But it does not seem to work as I expected. The either your code is somewhere outside of the try/except block when it receives SIGINT, the exception is being caught somewhere below the try/except clause that you added for KeyboardInterrupt, or there is something wrong with your handling code. If you want much more help, you are going to have to post some code to give us some specifics to troubleshoot.
From: Peter Otten on 11 Aug 2010 14:26
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 |