Python设置函数调用超时

http://blog.sina.com.cn/s/blog_63041bb80102uy5o.html

背景:

       最近写的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

    i = 0
    for i in range(1,10):
        try:
            signal.signal(signal.SIGALRM, handler)
            signal.alarm(3)
            test(i)
            i = i + 1
            signal.alarm(0)
        except AssertionError:
            print "%d timeout"%(i)
说明:
        1、调用test函数超时监控,使用sleep模拟函数执行超时
        2、引入signal模块,设置handler捕获超时信息,返回断言错误
        3、alarm(3),设置3秒闹钟,函数调用超时3秒则直接返回
        4、捕获异常,打印超时信息
 
程序执行结果:
1 within time
2 within time
3 timeout
4 within time
5 within time
6 within time
7 timeout
8 within time
9 within time
posted @ 2018-11-04 09:25  番茄土豆西红柿  阅读(5748)  评论(0编辑  收藏  举报
TOP