Python裝飾器限制函數(shù)運行時間超時則退出執(zhí)行
實際項目中會涉及到需要對有些函數(shù)的響應時間做一些限制,如果超時就退出函數(shù)的執(zhí)行,停止等待。
可以利用python中的裝飾器實現(xiàn)對函數(shù)執(zhí)行時間的控制。
python裝飾器簡單來說可以在不改變某個函數(shù)內(nèi)部實現(xiàn)和原來調(diào)用方式的前提下對該函數(shù)增加一些附件的功能,提供了對該函數(shù)功能的擴展。
方法一. 使用 signal
# coding=utf-8
import signal
import time
def set_timeout(num, callback):
def wrap(func):
def handle(signum, frame): # 收到信號 SIGALRM 后的回調(diào)函數(shù),第一個參數(shù)是信號的數(shù)字,第二個參數(shù)是the interrupted stack frame.
raise RuntimeError
def to_do(*args, **kwargs):
try:
signal.signal(signal.SIGALRM, handle) # 設置信號和回調(diào)函數(shù)
signal.alarm(num) # 設置 num 秒的鬧鐘
print('start alarm signal.')
r = func(*args, **kwargs)
print('close alarm signal.')
signal.alarm(0) # 關閉鬧鐘
return r
except RuntimeError as e:
callback()
return to_do
return wrap
def after_timeout(): # 超時后的處理函數(shù)
print("Time out!")
@set_timeout(2, after_timeout) # 限時 2 秒超時
def connect(): # 要執(zhí)行的函數(shù)
time.sleep(3) # 函數(shù)執(zhí)行時間,寫大于2的值,可測試超時
print('Finished without timeout.')
if __name__ == '__main__':
connect()
方法一中使用的signal有所限制,需要在linux系統(tǒng)上,并且需要在主線程中使用。方法二使用線程計時,不受此限制。
方法二. 使用Thread
# -*- coding: utf-8 -*-
from threading import Thread
import time
class TimeoutException(Exception):
pass
ThreadStop = 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 = _error
def run(self):
try:
self.result = function(*args,**kwargs)
except Exception,e:
self._error = str(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) # 設置運行超時時間2S
def fn_1(secs):
time.sleep(secs)
return 'Finished without timeout'
def do_something_after_timeout():
print('Time out!')
if __name__ == "__main__":
try:
print(fn_1(3)) # 設置函數(shù)執(zhí)行3S
except TimeoutException as e:
print(str(e))
do_something_after_timeout()
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內(nèi)容請查看下面相關鏈接
相關文章
Python使用matplotlib 模塊scatter方法畫散點圖示例
這篇文章主要介紹了Python使用matplotlib 模塊scatter方法畫散點圖,結(jié)合實例形式分析了Python數(shù)值運算與matplotlib模塊圖形繪制相關操作技巧,需要的朋友可以參考下2019-09-09
使用django-crontab實現(xiàn)定時任務的示例
這篇文章主要介紹了使用django-crontab實現(xiàn)定時任務,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02
DRF?QuerySet?Instance數(shù)據(jù)庫操作功能概述
這篇文章主要為大家介紹了DRF?QuerySet?Instance數(shù)據(jù)庫處理的功能概述,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10
Python issubclass和isinstance函數(shù)的具體使用
本文主要介紹了Python issubclass和isinstance函數(shù)的具體使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02

