本文實例講述了python使用裝飾器和線程限制函數執行時間的方法。分享給大家供大家參考。具體分析如下:
很多時候函數內部包含了一些不可預知的事情,比如調用其它軟件,從網絡抓取信息,可能某個函數會卡在某個地方不動態,這段代碼可以用來限制函數的執行時間,只需要在函數的上方添加一個裝飾器,timelimited(2)就可以限定函數必須在2秒內執行完成,如果執行完成則返回函數正常的返回值,如果執行超時則會拋出錯誤信息。
# -*- coding: utf-8 -*-from threading import Threadimport timeclass TimeoutException(Exception): passThreadStop = Thread._Thread__stop#獲取私有函數def timelimited(timeout): def decorator(function):def decorator2(*args,**kwargs):class TimeLimited(Thread):def __init__(self,_error= None,):Thread.__init__(self)self._error = _errordef run(self):try:self.result = function(*args,**kwargs)except Exception,e:self._error =edef _stop(self):if self.isAlive():ThreadStop(self)t = TimeLimited()t.start()t.join(timeout)if isinstance(t._error,TimeoutException):t._stop()raise TimeoutException('timeout for %s' % (repr(function)))if t.isAlive():t._stop()raise TimeoutException('timeout for %s' % (repr(function)))if t._error is None:return t.resultreturn decorator2 return decorator@timelimited(2)def fn_1(secs): time.sleep(secs) return 'Finished'if __name__ == "__main__": print fn_1(4)
希望本文所述對大家的Python程序設計有所幫助。
新聞熱點
疑難解答