超时装饰器

import functools
from threading import Thread

def timeout(timeout):
    '''
    从stackoverflow上找到的我自认为ok的超时装饰器,十分好用
    '''
    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 as e:
                    res[0] = e
            t = Thread(target=newFunc)
            t.daemon = True
            try:
                t.start()
                t.join(timeout)
            except Exception as je:
                print('error starting thread')
                raise je
            ret = res[0]
            if isinstance(ret, BaseException):
                raise ret
            return ret
        return wrapper
    return deco

posted @ 2021-01-25 21:52  P-Z-W  阅读(40)  评论(0编辑  收藏  举报