Catching control-C

Ben Charrow bcharrow at csail.mit.edu
Mon Jul 6 18:38:12 EDT 2009


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.

You don't need to be doing I/O in order to raise a KeyboardIneterrupt.  For
example, the following program should use up a lot of your CPU until you
hit Ctrl-C.

>>> while True:
...     pass
...
^CTraceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyboardInterrupt

> In the past, I've written Python programs that go about their business 
> ignoring Ctrl-C.

Can you be more specific?  Can you share the relevant sections of these
programs?  Were these programs multi-threaded?

> But I want to understand better what the "secret" is to responding to a 
> ctrl-C in any shape or form.

Strictly speaking, I don't think you can always respond to a Ctrl-C in any
shape or form.  Quoting from the signal module:

Although Python signal handlers are called asynchronously as far as the Python
user is concerned, they can only occur between the "atomic" instructions of the
Python interpreter. This means that signals arriving during long calculations
implemented purely in C (such as regular expression matches on large bodies of
text) may be delayed for an arbitrary amount of time.

HTH,
Ben




More information about the Python-list mailing list