Catching control-C

Lie Ryan lie.1296 at gmail.com
Thu Jul 9 09:20:19 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. In the
> past, I've written Python programs that go about their business
> ignoring Ctrl-C. Other programs respond to it immediately by exiting.
> I think the difference is that the latter programs are doing i/o. But
> I want to understand better what the "secret" is to responding to a
> ctrl-C in any shape or form.
> 
> For example, does trapping SIGINT always work, regardless of what my
> process is doing?
> 
> Thanks,
> Mike

Are you asking: "when would the python interpreter process
KeyboardInterrupt?"

In a multi threaded python program (where KeyboardInterrupt doesn't
always work), only the main thread can process KeyboardInterrupt; thus
the main thread must regain control before the interrupt is raised.
Normally, python will context switch (i.e. thread switch) every 100
interpreter "ticks", but when the interpreter received a SIGINT, the
interpreter will try to context switch as fast as it can (every tick) to
allow the main thread to regain control. So the answer is in
multithreaded python program: "when the main thread regains control"

In single threaded python program, the currently running thread is
always the main thread (which can handle KeyboardInterrupt). I believe
SIGINT is checked at every ticks. But SIGINT cannot interrupt atomic
operations (i.e. it cannot interrupt long operations that takes a single
tick).

An example, where python have difficulties processing KeyboardInterrupt:
>>> print 'foo'*10000000
...foofoofoo...
because printing a string is an atomic operation

I believe a tick in python is equivalent to a single bytecode, but
please correct me if I'm wrong.



More information about the Python-list mailing list