Interrupting a running python thread

johan2sson at gmail.com johan2sson at gmail.com
Fri Aug 25 18:25:37 EDT 2006


I have embedded a python console in a plugin to a Windows application.
I do not control the application, but the plugin is mine. Since the
application is not thread-safe, I am push()-ing each line onto a
code.InteractiveConsole on the GUI thread. This has the downside that a
silly mistake that creates an infinite loop also hangs the GUI, thus
preventing you from saving your work or exiting the application in any
normal fashion.

As a workaround, I've installed a console handler that calls
thread.interrupt_main() when control-c is pressed. I should point out
that this is done on a new thread. Unfortunately this doesn't work at
all. Without returning from the last call to InteractiveConsole.push()
or catching the KeyboardInterrupt, the interpreter explodes with a "no
current thread" fatal error.

I've tried the exact same code at "the real" python prompt and that
happily prints:

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyboardInterrupt
>>>

The code used is this infinite loop:

a = 0
while a == 0: b = a + 2

What's the secret? The only use of SetConsoleCtrlHandler I could find
in the CPython source didn't make me much wiser.

Johan




More information about the Python-list mailing list