背景:
最近写的Python代码不知为何,总是执行到一半卡住不动,为了使程序能够继续运行,设置了函数调用超时机制。
代码:
import time
import signal
def test(i):
time.sleep(i % 4)
print "%d within time" % (i)
return i
if __name__ == '__main__':
def handler(signum, frame):
raise AssertionError
for i in range(1, 10):
try:
signal.signal(signal.SIGALRM, handler)
signal.alarm(3)
test(i)
except AssertionError:
print "%d timeout" % (i)
finally:
signal.alarm(0)
signal.signal(signal.SIGALRM, signal.SIG_DFL)
说明:
1、调用test函数超时监控,使用sleep模拟函数执行超时
2、引入signal模块,设置handler捕获超时信息,返回断言错误
3、alarm(3),设置3秒闹钟,函数调用超时3秒则直接返回
4、捕获异常,打印超时信息
程序执行结果:
1 within time2 within time3 timeout4 within time5 within time6 within time7 timeout8 within time9 within time博客原文:http://blog.sina.com.cn/s/blog_63041bb80102uy5o.html