程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python exception automatic retry --retrying

編輯:Python

Usually, the program is terminated to prevent exceptions , We will adopt try To get exceptions .
Column such as calling a third party API, Exceptions may occur even if the device status heartbeat is reported and the network is unstable .
We want to automatically repeat the call or specify the number of calls when an exception occurs in the program .
python retrying library , Perfect realization of this requirement .
retrying Provide a decorator function retry, The decorated function will execute again in case of failure , By default, if the error is reported all the time, try again .

Installation Library pip install retrying

from retrying import retry
import time

1. Infinite retries

@retry()
def run():
print(' Repeated calls to ')
time.sleep(1)
raise Exception

2. max retries stop_max_attempt_number

@retry(stop_max_attempt_number=5)
def run():
print(' Repeated calls to ')
time.sleep(1)
raise Exception

3. Maximum retry time stop_max_delay Unit millisecond

@retry(stop_max_delay=5000)
def run():
print(' Repeated calls to ')
time.sleep(1)
raise Exception

4. Retry interval wait_fixed Unit millisecond

@retry(wait_fixed=5000)
def run():
print(' Repeated calls to ')
raise Exception

5. Retry while calling another method stop_func

# Parameters attempts, delay mandatory 
def log_error(attempts, delay):
print(' Record exceptions ')
# Specify the exception to call the function repeatedly 
@retry(stop_func=log_error)
def run():
print(' Repeated calls to ')
time.sleep(1)
raise Exception
if __name__ == '__main__':
run()


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved