python调用函数设置超时机制

2023-10-15,,

有时候需要给函数设置超时机制,以防止它卡住我们的程序,这里可以用python的signal模块,signal模块可以实现程序内部的信号处理。

# coding:utf8
import time
import signal # 自定义超时异常
class TimeoutError(Exception):
def __init__(self, msg):
super(TimeoutError, self).__init__()
self.msg = msg def time_out(interval, callback):
def decorator(func):
def handler(signum, frame):
raise TimeoutError("run func timeout") def wrapper(*args, **kwargs):
try:
signal.signal(signal.SIGALRM, handler)
signal.alarm(interval) # interval秒后向进程发送SIGALRM信号
result = func(*args, **kwargs)
signal.alarm(0) # 函数在规定时间执行完后关闭alarm闹钟
return result
except TimeoutError, e:
callback(e)
return wrapper
return decorator def timeout_callback(e):
print(e.msg) @time_out(2, timeout_callback)
def task1():
print("task1 start")
time.sleep(3)
print("task1 end") @time_out(2, timeout_callback)
def task2():
print("task2 start")
time.sleep(1)
print("task2 end") if __name__ == "__main__":
task1()
task2()

输出为:

>>> task1 start
>>> run func timeout
>>> task2 start
>>> task2 end

可以看到,虽然task1超时了,但是它不会影响我们程序的执行。

另外信号机制只能在主线程中生效, 意味着你不能在多线程中使用它,python已经很好的支持了协程,因此我们可以使用协程代替多线程。

python调用函数设置超时机制的相关教程结束。

《python调用函数设置超时机制.doc》

下载本文的Word格式文档,以方便收藏与打印。