views:

84

answers:

1
+1  Q: 

Python kill thread

I'm trying to kill a thread in python. An exception would be the preferred way to do it, as a graceful exit of the run method of the thread through a try:except: pair would allow to close resources.

I tried : http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python , but is specifies that is doesn't work while the code is executing a system call (like time.sleep). Is there a way to raise an exception in another thread (or process, in don't mind,) that work no mater what the thread is executing?

+2  A: 

In general, raising asynchronous exceptions is difficult to handle properly. This is because, rather than having single, specific points of code where an exception may be generated--and therefore where exception handling needs to be tested--instead, an exception may be generated after any bytecode instruction. This makes it much harder to implement and fully test exception handling.

That said, it can be done--but, presently, not safely in Python. Raising an exception asynchronously in Python is dangerous, because you might raise it during an exception handler, which will raise another exception and prevent cleanup from occurring properly. See my answer at http://stackoverflow.com/questions/366682.

It's possible to signal some forms of sleep to cancel, but there's no general infrastructure for this in Python. You're much better off either avoiding the need to kill a thread, or moving the thread to a process, where you can send a signal to the whole process and exit cleanly.

Glenn Maynard