我們知道Exception Handlingpython中的標準:
def fun():
a = 1
x = 5
......
......
try:
print(x)
except:
print("An exception occurred")
......
......
return x a
我想實作這一目標
- 如果
try失敗,我們將立即重試;如果try第二次失敗,我們會去except。 - 如果
try失敗,我們將在 1 分鐘后重試;如果try第二次失敗,我們會去except。
你能給我一些關于python中重試函式的參考嗎?
uj5u.com熱心網友回復:
嘗試retry包裝中的裝飾器retry
https://pypi.org/project/retry/
pip install retry
然后
from retry import retry
@retry(ZeroDivisionError, tries=4, delay=2, backoff=2)
def make_trouble():
'''Retry on ZeroDivisionError, raise error after 3 attempts, sleep 2 seconds between attempts.'''
print(f'trying {1.0/0.0}')
make_trouble()
uj5u.com熱心網友回復:
我沒有聽說過任何重試功能,但是您可以使用回圈來實作幾乎相同的事情
while true:
try:
print(x)
break
except:
pass
uj5u.com熱心網友回復:
既然您在函式中使用了那段代碼,那么如果出現例外,為什么不再次呼叫該函式呢?
我也猜想如果出現錯誤你不想回傳任何東西,所以這里是第一個條件的代碼:
def fun(repeated=False):
a = 1
x = 5
try:
print(x)
return x a
except:
if times_repeated:
print("An exception occurred")
else:
print("Trying again")
fun(repeated=True)
fun()
第二個條件的代碼:
import time
def fun(repeated=False):
if times_repeated:
time.sleep(60)
a = 1
x = 5
try:
print(x)
return x a
except:
if times_repeated:
print("An exception occurred")
else:
print("Trying again in 60 seconds")
fun(repeated=True)
fun()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/529622.html
標籤:Python例外
上一篇:通過JSON將函式名稱和引數作為字串傳遞給服務器,并在服務器上呼叫該函式
下一篇:ControllerAdvice在SpringSecurity之前捕獲AuthenticationException
