I think a good way to get closer to this is to create a decorator and use the Thread.join (timeout) method. keep in mind that there is no good way to kill a thread, so it will continue to run in the background, more or less if your program is running.
first create a decorator as follows:
from threading import Thread import functools def timeout(timeout): def deco(func): @functools.wraps(func) def wrapper(*args, **kwargs): res = [Exception('function [%s] timeout [%s seconds] exceeded!' % (func.__name__, timeout))] def newFunc(): try: res[0] = func(*args, **kwargs) except Exception, e: res[0] = e t = Thread(target=newFunc) t.daemon = True try: t.start() t.join(timeout) except Exception, je: print 'error starting thread' raise je ret = res[0] if isinstance(ret, BaseException): raise ret return ret return wrapper return deco
then do something like this:
func = timeout(timeout=16)(MyModule.MyFunc) try: func() except: pass
You can use this decorator anywhere you need:
@timeout(60) def f(): ...
acushner
source share