1. 程式人生 > >Python設定函式呼叫超時

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