安裝: pip install retrying
@retry 裝飾器會對函式不斷的重試
#預設無限重試
@retry(
)def
pick_one()
:print
('pick'
) t = random.randint(0,
2)print
(t)if t !=1:
raise exception(
'1 is not picked'
)if __name__ ==
'__main__'
:'''
'''pick_one(
)#隨機數不等於1則一直重試,等於1則停止
1、retry(wait_fixed =
1000
)#設定重試間隔時長(ms 1000ms = 1s)
2、retry(wait_random_min =
1000
,wait_random_max =
2000,)
#隨機重試間隔,將在1~2s內
3、retry(stop_max_attempt_number =3)
#最大重試次數,超過後正常丟擲異常
4、retry(stop_max_delay =
2000
)#最大延遲時長,2s內未滿足條件則丟擲異常
5、retry(wait_exponential_multiplier =
,wait_exponential_max =
)#以指數的形式產生兩次retrying之間的停留時間。wait_exponential_multiplier和wait_exponential_max:以指數的形式產生兩次retrying之間的停留時間,產生的值為
(2^previous_attempt_number * wait_exponential_multiplier),
previous_attempt_number是前面已經retry的次數,如果
產生的這個值超過了wait_exponential_max的大小,那麼之後兩個retrying之間的停留值都為wait_exponential_max。這個設計迎合
了exponential backoff演算法,可以減輕阻塞的情況
6、retry(retry_on_exception = 函式)
#當發生指定異常時才會重試
#--------------
defmy_exc2
(exc)
:return
isinstance
(exc,zerodivisionerror)
@retry(retry_on_exception = my_exc2)
defpick_one()
:# sleep(2)
print
('pick'
) t = random.randint(0,
2)print
(t)if t !=1:
a =1/
0if __name__ ==
'__main__'
:'''
'''pick_one(
)#當發生zerodivisionerror時才會重試,其他異常不會重試
7、retry(retry_on_result = 函式)
#對結果的判定 將被修飾函式的返回值傳人函式,如果函式返回true則重試
#--------------
defmy_res
(result)
:print
(result)
return
isinstance
(result,
str)
@retry(retry_on_result = my_res)
defpick_one()
:print
('pick'
) t = random.randint(0,
2)print
(t)if t !=1:
return
'100'
if __name__ ==
'__main__'
:'''
'''pick_one(
)#t != 1 時pick_one返回『100』,my_res返回true 則重試
8、retry(stop_func = 函式)
#每次丟擲異常時都會執行的函式,如果和stop_max_delay、stop_max_attempt_number配合使用,則後兩者會失效,指定的stop_func會有兩個引數:attempts, delay
#--------------
defstop_fun
(attempts, delay)
:print
("stop_func %d--->%d"
%(attempts,delay)
)@retry(stop_func = stop_fun)
defpick_one()
: t = random.randint(0,
2)if t !=
1or t ==1:
a =1/
0raise exception(filenotfounderror(
'1 is not picked'))
if __name__ ==
'__main__'
:'''
'''pick_one(
) wait_fixed =
none
Python的重試模組
我們寫 的時候,經常會用到重試,如果出錯了,或者出現了其他的問題,就重試一次或者n次,自己寫實現起來比較複雜,用retrying模組就可以很容易的解決了。1 pip install retrying 安裝 下面是幾個重試的例子,直接看 import requests from retrying im...
Python的異常重試方法
專案msb服務不穩定,通過python建立websocket總是會有問題,很不穩定,但是一般來說重新建立連線就能成功,多嘗試幾次就好了。既然有了相應的需求,就要考慮如何去解決這個websocket建立異常重試的問題 原來的 只建立了一次websocket連線 ws.connect url,heade...
Python出錯重試 retrying
在編寫python 進行自動化測試 網路爬蟲或者其他與網路相關的動作的時候,由於網路影響會容易失敗,而這種失敗並不是我們需要去處理的。那麼這種時候最好的辦法就是失敗後重試幾次,以避免網路的間斷性影響。如果我們正常編寫 的話,可能需要 try except 但是這種寫法很麻煩,能實現的效果也很單一。這...