views:

2128

answers:

2
+6  Q: 

Python Timeout

I've been looking all over the place for a good timeout script that can kill a thread if it's been active for more than X seconds, but all the examples I've seen have flaws that don't always stop the thread. Using thread.join(x) ends up defeating the purpose of it being a thread.

The only decent example I've found is http://stackoverflow.com/questions/492519/timeout-on-a-python-function-call and that one's not without its flaws..

Anyone know of a better way to do this?

A: 

I know this might not be what you want, but have you considered the signal approach? http://stackoverflow.com/questions/492519/timeout-on-a-python-function-call/494273#494273 http://docs.python.org/library/signal.html#example

You can set an alarm signal at the beginning of the thread execution, and then stop the thread in the signal handler.

Nadia Alramli
> This module doesn't play well with threads (but then, who does?)
Dave
+1  A: 

See my answer to python: how to send packets in multi thread and then the thread kill itself - there is a fragment with InterruptableThread class and example that kill another thread after timeout - exactly what you want.

There is also similar Python recipe at activestate.

Jiri