自定义装饰器运行报错
装饰器实现的是检测其他线程代码超时的功能但是定义两层不知道该返回什么就会报错 三层就没问题,求解答
正常执行代码:
import threading
import time
def watchdog(thread, timeout):
time.sleep(timeout)
if thread.is_alive():
print("Thread timed out")
# Terminate the thread
thread.stop = True
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("Main thread finished")
return wrapper
return decorator
@watchdog_decorator(3)
def test():
time.sleep(10)
if __name__ == "__main__":
test()
报错代码:
import threading
import time
def watchdog(thread, timeout):
time.sleep(timeout)
if thread.is_alive():
print("Thread timed out")
# Terminate the thread
thread.stop = True
def watchdog_decorator(timeout):
def decorator(func):
thread = threading.Thread(target=func)
thread.start()
watchdog_thread = threading.Thread(target=watchdog, args=(thread, timeout))
watchdog_thread.start()
thread.join()
print("Main thread finished")
return decorator
@watchdog_decorator(3)
def test():
time.sleep(10)
if __name__ == "__main__":
test()
第二段代码在不增加装饰器里的函数的情况下该怎样更改才能使代码不会报错呢 decorator函数应该返回什么