Python检测超时代码(windows、linux通用)

from threading import Thread
import functools
import time

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 as e:
                    res[0] = e
            t = Thread(target=newFunc)
            t.daemon = True
            try:
                t.start()
                t.join(timeout)
            except:
                print('error starting thread')
            ret = res[0]
            if isinstance(ret, BaseException):
                print('timeout')
            return ret
        return wrapper
    return deco

@timeout(3)
def f():
    time.sleep(5)
    print('f')

f()

发表评论

电子邮件地址不会被公开。 必填项已用*标注

This blog is kept spam free by WP-SpamFree.