利用signal模块,可以给函数设置一个超时时间(精确到秒),结合装饰器实现:超时时间内函数运行完成正常退出,超时时间内函数未运行完成则抛出Timeout异常。
1 # coding:utf8 2 import time 3 import signal 4 5 6 # 自定义超时异常 7 class TimeoutError(Exception): pass 8 9 # 超过超时时间,调用此函数 10 def handler(signum, frame): 11 raise TimeoutError() 12 13 # 函数超时装饰器 14 def time_out(interval, doc): 15 def decorator(func): 16 def wrapper(*args, **kwargs): 17 try: 18 signal.signal(signal.SIGALRM, handler) 19 signal.alarm(interval) # interval秒后向进程发送SIGALRM信号 20 result = func(*args, **kwargs) 21 signal.alarm(0) # 函数在规定时间执行完后关闭alarm闹钟 22 return result 23 except TimeoutError as e: 24 # 捕获到超时异常,要做的事情 25 print("The function failed to run due to timeout, func:<%s>" % doc) 26 return wrapper 27 return decorator 28 29 @time_out(1, "demo.py中task1函数") 30 def task1(): 31 print("task1 start") 32 time.sleep(1.2) 33 print("task1 end") 34 35 36 @time_out(1, "demo.py中task2函数") 37 def task2(): 38 print("task2 start") 39 time.sleep(0.8) 40 print("task2 end") 41 42 43 if __name__ == "__main__": 44 task1() 45 task2() 46 47 48 # task1 start 49 # The function failed to run due to timeout, func:<demo.py中task1函数> 50 # task2 start 51 # task2 end