Catching control-C

Nick Craig-Wood nick at craig-wood.com
Wed Jul 8 06:30:01 EDT 2009


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote:
>  On Mon, 06 Jul 2009 15:02:26 -0700, Michael Mossey wrote:
> 
> > On Jul 6, 2:47 pm, Philip Semanchuk <phi... at semanchuk.com> wrote:
> >> On Jul 6, 2009, at 5:37 PM, Michael Mossey wrote:
> >>
> >> > What is required in a python program to make sure it catches a
> >> > control-
> >> > c on the command-line? Do some i/o? The OS here is Linux.
> >>
> >> You can use a try/except to catch a KeyboardInterrupt exception, or you
> >> can trap it using the signal
> >> module:http://docs.python.org/library/signal.html
> >>
> >> You want to trap SIGINT.
> >>
> >> HTH
> >> Philip
> > 
> > Thanks to both of you. However, my question is also about whether I need
> > to be doing i/o or some similar operation for my program to notice in
> > any shape or form that Control-C has been pressed. In the past, I've
> > written Python programs that go about their business ignoring Ctrl-C.
> 
>  I bet that somewhere in your code you have something like:
> 
> 
>  for x in really_big_list:
>      try:
>          long_running_process(x)
>      except:
>          continue
> 
> 
>  If that's what you're doing, stop! The correct way is:
> 
> 
>  for x in really_big_list:
>      try:
>          long_running_process(x)
>      except Exception:
>          # Let KeyboardInterrupt and SystemExit through.
>          continue

Note that it is a relatively recent change (in python 2.5) which made
KeyboardInterrupt not a child of Exception

ncw at dogger:~$ python2.4
Python 2.4.6 (#2, Feb 17 2009, 20:01:48)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Loaded customisations from '/home/ncw/.pystartup'
>>> isinstance(KeyboardInterrupt(), Exception)
True
>>>

ncw at dogger:~$ python2.5
Python 2.5.4 (r254:67916, Feb 17 2009, 20:16:45)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Loaded customisations from '/home/ncw/.pystartup'
>>> isinstance(KeyboardInterrupt(), Exception)
False
>>>

>  for x in really_big_list:
>      try:
>          long_running_process(x)
>      except (KeyboardInterrupt, SystemExit):
>          print "User requested exit... shutting down now"
>          cleanup()
>          raise
>      except Exception:
>          continue

That is the backwards compatible way

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list