本文實(shí)例講述了python使用裝飾器和線程限制函數(shù)執(zhí)行時(shí)間的方法。分享給大家供大家參考。具體分析如下:
很多時(shí)候函數(shù)內(nèi)部包含了一些不可預(yù)知的事情,比如調(diào)用其它軟件,從網(wǎng)絡(luò)抓取信息,可能某個(gè)函數(shù)會(huì)卡在某個(gè)地方不動(dòng)態(tài),這段代碼可以用來限制函數(shù)的執(zhí)行時(shí)間,只需要在函數(shù)的上方添加一個(gè)裝飾器,timelimited(2)就可以限定函數(shù)必須在2秒內(nèi)執(zhí)行完成,如果執(zhí)行完成則返回函數(shù)正常的返回值,如果執(zhí)行超時(shí)則會(huì)拋出錯(cuò)誤信息。
# -*- coding: utf-8 -*-from threading import Threadimport timeclass TimeoutException(Exception): passThreadStop = Thread._Thread__stop#獲取私有函數(shù)def timelimited(timeout): def decorator(function): def decorator2(*args,**kwargs): class TimeLimited(Thread): def __init__(self,_error= None,): Thread.__init__(self) self._error = _error def run(self): try: self.result = function(*args,**kwargs) except Exception,e: self._error =e def _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.result return decorator2 return decorator@timelimited(2)def fn_1(secs): time.sleep(secs) return 'Finished'if __name__ == "__main__": print fn_1(4)希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選