python timeout装饰器

?

class TimedOutExc(Exception):    """    Raised when a timeout happens    """def timeout(timeout):    """    Return a decorator that raises a TimedOutExc exception    after timeout seconds, if the decorated function did not return.    """    def decorate(f):        def handler(signum, frame):            raise TimedOutExc()        def new_f(*args, **kwargs):            old_handler = signal.signal(signal.SIGALRM, handler)            signal.alarm(timeout)            result = f(*args, **kwargs)  # f() always returns, in this scheme            signal.signal(signal.SIGALRM, old_handler)  # Old signal handler is restored            signal.alarm(0)  # Alarm removed            return result        new_f.func_name = f.func_name        return new_f    return decorate@timeout(10)def function_that_takes_a_long_time():    try:        # ... long, parallel calculation ...    except TimedOutExc:        # ... Code that shuts down the processes ...        # ...        return None  # Or exception raised, which means that the calculation is not complete

出自:http://stackoverflow.com/questions/8616630/time-out-decorator-on-a-multprocessing-function

python timeout装饰器

相关文章:

你感兴趣的文章:

标签云: