How to get a raised exception from other thread

Alex Martelli aleaxit at yahoo.com
Mon Oct 17 04:29:42 EDT 2005


<themightydoyle at gmail.com> wrote:

> Nevermind.  I found a better solution.  I used shared memory to create
> a keep-alive flag.  I then use the select function with a specified
> timeout, and recheck the keep-alive flag after each timeout.

Definitely a better architecture.  Anyway, one supported way for a
thread to raise an exception in a different thread is function
thread.interrupt_main(), which raises a KeyboardInterrupt in the *main*
thread (the one thread that's running at the beginning of your program).

There's also a supported, documented function to raise any given
exception in any existing thread, but it's deliberately NOT directly
exposed to Python code -- you need a few lines of  C-coded extension (or
pyrex, ctypes, etc, etc) to get at the functionality.  This small but
non-null amount of "attrition" was deliberately put there to avoid
casual overuse of a facility intended only to help in very peculiar
cases (essentially in debuggers &c, where the thread's code may be buggy
and fail to check a keep-alive flag correctly...!-).


Alex



More information about the Python-list mailing list