Trace KeyboardInterrupt exception?
andrewdalke at gmail.com
andrewdalke at gmail.com
Wed Jun 14 10:01:42 EDT 2006
Tony Nelson wrote:
> I'm trying to find out what is eating some KeyboardInterrupt exceptions
> in a fairly large program (yum). My KeyboardInterrupt handler is called
> for some Ctl-C presses, but for others nothing seems to happen.
> ... I'd like to use a debugger to trace
> KeyboardInterrupt exceptions, make sure that they're happening, and see
> what is handling them.
I don't know how to do that in Idle. You can replace the default
Ctrl-C interrupt
handler with your own and use that to inspect the current stack. For
example,
>>> import signal
>>> signal.getsignal(signal.SIGINT)
<built-in function default_int_handler>
>>> prev_handler = signal.getsignal(signal.SIGINT)
>>> def new_int_handler(*args):
... print "Keyboard Interrupt!"
... traceback.print_stack()
... prev_handler(*args)
...
>>> signal.signal(signal.SIGINT, new_int_handler)
<built-in function default_int_handler>
>>> def spin():
... while 1: pass
...
>>> import traceback
>>> spin()
^CKeyboard Interrupt!
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in spin
File "<stdin>", line 3, in new_int_handler
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in spin
File "<stdin>", line 4, in new_int_handler
KeyboardInterrupt
>>>
There's no real need to call the old handler. You could "raise
KeyboardInterrupt"
or SystemExit or just ignore it, as in
>>> count = 0
>>> def new_int_handler(signum, frame):
... global count
... print messages[count]
... if count >= len(messages)-1:
... raise KeyboardInterrupt
... count += 1
...
>>> messages = {0: "Sorry, did you want me to do something?",
... 1: "That's ticklish!",
... 2: "Now, where did that off button go to....",
... 3: "Do that again and I'll leave.",
... 4: "Shutdown activated"}
>>>
>>> def spin():
... while 1: pass
...
>>> spin()
^CTraceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in spin
KeyboardInterrupt
>>>
>>> import signal
>>> signal.signal(signal.SIGINT, new_int_handler)
<built-in function default_int_handler>
>>>
>>> spin()
^CSorry, did you want me to do something?
^CThat's ticklish!
^CNow, where did that off button go to....
^CDo that again and I'll leave.
^CShutdown activated
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in spin
File "<stdin>", line 5, in new_int_handler
KeyboardInterrupt
>>>
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list