自定义装饰器——代码超时检测
"""
@author:T
@email:ttbjsht@163.com
@File:time_out_decorator
@descr:
@Created on:2023/2/13/09:59
@IDE:PyCharm
"""
import threading
import time
def watchdog(thread, timeout) -> None:
'''
检测装饰器装饰函数对象是否超时
:param thread: 被检测的对象 被检测对象是个可执行函数使用多线程来执行函数的功能 (如果不使用多线程的话会阻塞无法同时检测运行时间 )
:param timeout: 定义超时时间
:return: None
'''
time.sleep(timeout)
if thread.is_alive():
print(f'{thread.name} timeout')
return
def watchdog_decorator(timeout):
def decorator(func):
def wrapper(*args, **kwargs):
thread = threading.Thread(target=func, args=args, kwargs=kwargs)
thread.start()
watchdog_thread = threading.Thread(target=watchdog, args=(thread, timeout))
watchdog_thread.start()
thread.join()
print("主线程运行结束")
return wrapper
return decorator
@watchdog_decorator(2)
def test():
print('test函数开始执行')
time.sleep(3)
print('test函数执行结束')
if __name__ == '__main__':
test()