I have this decorator:
def timed_out(timeout):
def decorate(f):
if not hasattr(signal, "SIGALRM"):
return f
def handler(signum, frame):
raise TimedOutExc()
@functools.wraps(f)
def new_f(*args, **kwargs):
old = signal.signal(signal.SIGALRM, handler)
signal.alarm(timeout)
try:
result = f(*args, **kwargs)
finally:
signal.signal(signal.SIGALRM, old)
signal.alarm(0)
return result
new_f.func_name = f.func_name
return new_f
return decorate
The code only does anything on linux, though, as on windows, there is no SIGALRM
. What would be the simplest way to have this code work in Windows as well?
It's not very pretty, but I had to do something similar in a cross-platform way, and I came up with using a separate thread. Signal based systems did not work on all platforms reliably.
Use of this class could be wrapped up in a decorator, or made into a
with
context handler.YMMV.
I find this timeout-decorator code very handy, too. (I originally found it in this question answer: How to limit execution time of a function call in Python)
To make it work on Windows, I use the Python that is installed with Cygwin.
I run setup-x86_64.exe, then select the
python3
package from the Python folder. (Or, if you prefer Python 2, thepython
package.)To rename python3 to python2, I define the alias
from the Cygwin command prompt. Since I don't use this functionality very often, I probably won't put it into a .bashrc or anything.
Related question: Python signal don't work even on Cygwin?