Python设置函数调用超时,进程卡住

2020-01-09 17:02:07 浏览数 (1)

背景:

       最近写的Python代码不知为何,总是执行到一半卡住不动,为了使程序能够继续运行,设置了函数调用超时机制。

代码:

代码语言:javascript复制
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 time 2 within time 3 timeout 4 within time 5 within time 6 within time 7 timeout 8 within time 9 within time 博客原文:http://blog.sina.com.cn/s/blog_63041bb80102uy5o.html

0 人点赞