I looked online and found some SO discussing and ActiveState recipes for running some code with a timeout. It looks there are some common approaches:
- Use thread that run the code, and
join
it with timeout. If timeout elapsed - kill the thread. This is not directly supported in Python (used private_Thread__stop
function) so it is bad practice - Use
signal.SIGALRM
- but this approach not working on Windows! - Use subprocess with timeout - but this is too heavy - what if I want to start interruptible task often, I don't want fire process for each!
So, what is the right way? I'm not asking about workarounds (eg use Twisted and async IO), but actual way to solve actual problem - I have some function and I want to run it only with some timeout. If timeout elapsed, I want control back. And I want it to work on Linux and Windows.
For "normal" Python code, that doesn't linger prolongued times in C extensions or I/O waits, you can achieve your goal by setting a trace function with
sys.settrace()
that aborts the running code when the timeout is reached.Whether that is sufficient or not depends on how co-operating or malicious the code you run is. If it's well-behaved, a tracing function is sufficient.
I found this with eventlet library:
http://eventlet.net/doc/modules/timeout.html
I've solved that in that way: For me is worked great (in windows and not heavy at all) I'am hope it was useful for someone)
The main idea is to create a thread that will just sleep in parallel to "long work" and in wake up (after timeout) change the secured variable state, the long function checking the secured variable during its work. I'm pretty new in Python programming, so if that solution has a fundamental errors, like resources, timing, deadlocks problems , please response)).
An other way is to use faulthandler:
N.B: The faulthandler module is part of stdlib in python3.3.
What you might be looking for is the multiprocessing module. If
subprocess
is too heavy, then this may not suit your needs either.If it's network related you could try: