python 超时装饰器

时间:2021-08-19
本文章向大家介绍python 超时装饰器,主要包括python 超时装饰器使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

#************************************************************** 设置超时的装饰器 **************************************************************

# 装饰器设置超时时间
# class TimeoutException(Exception):
# pass
# ThreadStop = Thread._Thread__stop
#
# def set_timeout_limit(timeout):
# def decorator(function):
# def decorator2(*args, **kwargs):
# class TimeLimited(Thread):
# def __init__(self, _error=None, ):
# Thread.__init__(self)
# self._error = _error
#
# def run(self):
# try:
# self.result = function(*args, **kwargs)
# except Exception, e:
# self._error = str(e)
#
# def _stop(self):
# if self.isAlive():
# ThreadStop(self)
#
# t = TimeLimited()
# t.start()
# t.join(timeout)
# if isinstance(t._error, TimeoutException):
# t._stop()
# raise TimeoutException('timeout for %s' % (repr(function)))
# if t.isAlive():
# t._stop()
# raise TimeoutException('timeout for %s' % (repr(function)))
# if t._error is None:
# return t.result
# return decorator2
# return decorator

# # 装饰器设置超时时间
# def set_timeout_limit(t):
# def auto_quit(t1):
# '''此为控制进程超时退出的线程函数'''
# time.sleep(t1)
# print("time out {}".format(t1))
# os._exit(1) #此函数专门用于线程控制主进程退出,有兴趣的可以看一下和sys.exit()的区别
# def decorator(f):
# '''此函数用于传入被装饰函数f'''
# @wraps(f)
# def wrapper(*args,**kwargs):
# '''装饰器内部遵循的逻辑是:
# 1.auto_quit先执行完,进程结束
# 2.被修饰函数f先执行完,auto_quit函数停止执行
# 3.被修饰函数执行完,下面的代码才能运行
# '''
# t1=Thread(target=auto_quit,args=(t,)) #此处的t是set_time_limit函数的形参,是auto_quit函数的实参
# t2=Thread(target=f,args=args,kwargs=kwargs)
# t1.setDaemon(True) #满足第2点
# t1.start()
# t2.start()
# t2.join() #满足第3点
# return wrapper
# return decorator

***还有一种方法,多线程设置成守护线程。主线程退出,其他线程也会退出。达到超时退出的目的。

原文地址:https://www.cnblogs.com/xlw-blogs/p/15162891.html