安裝
pip install retrying
簡單使用
import random from retrying import retry @retry def do_something_unreliable(): if random.randint(0, 10) > 1: print("just have a test") raise IOError("raise exception!") else: return "good job!" print(do_something_unreliable())
其他參數
# 最大重試次數 @retry(stop_max_attempt_number=5) # 限制最長重試時間(從執行方法開始計算) @retry(stop_max_delay=5000) # 設置固定重試時間 @retry(wait_fixed=2000) # 設置重試時間的隨機範圍 @retry(wait_random_min=1000,wait_random_max=2000) # 根據異常重試 def retry_if_io_error(exception): return isinstance(exception, IOError) # 設置特定異常類型重試 @retry(retry_on_exception=retry_if_io_error) # 通過返回值判斷是否重試 def retry_if_result_none(result): """Return True if we should retry (in this case when result is None), False otherwise""" # return result is None if result =="111": return True @retry(retry_on_result=retry_if_result_none)