How do i : Python Threads + KeyboardInterrupt exception

Brendon Costa brendon at christian.net
Thu Jun 19 06:33:42 CEST 2008


> I don't know the "standard" way, but perhaps you can get some ideas from
> this recent thread:http://groups.google.com/group/comp.lang.python/browse_thread/thread/...
>

I had a quick read through that thread. I think i will need some more
time to think about what they are saying in there though. They seem to
talking about killing a python thread kind of similar to the C
functions TerminateThread() in windows or pthread_cancel() on UNIX
which are not suitable for my purpose.


> You might try using the PyThreadState_SetAsyncExc function (from the
> Python C API) to inject a KeyboardInterrupt exception into the Read thread
> - but I don't know if it will work at all, the execution might be blocked
> waiting for an I/O call to complete, and never return to Python code...
>

Unfortunately that is the problem. It is blocking in a IO system call
and i want to force it to exit that with an error, hopefully causing a
Python exception. I looked at what you mentioned and it is described a
bit here too: http://sebulba.wikispaces.com/recipe+thread2

I really need a python mechanism for interrupting blocking system
calls.  have dealt with this sort of thing before in C/C++ on windows
and UNIX. For UNIX it is really a matter of sending a signal to the
process (SIGINTR), the main thread which is the only one in Python to
accept signals (others as i understand are masked) will get the signal
and and return with an EINTR breaking out of the blocking read
hopefully a python exception of Interrupted IO or KeyboardInterrupt.
Note that this only works for the one thread , but that is all i need.

For windows, it is possible to do a similar thing using:
GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, 0) with which behaves a bit
like a UNIX signal and i assume is what causes the KeyboardInterrupt
in the first place.

The problem i have is how do I achieve this in python?



More information about the Python-list mailing list