Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

try...except 语句里,执行完 except 怎么回去执行 try ?

def doSth():
    ...
    
try:
    doSth()
except:
    print("requests speed so high,need sleep!")
    time.sleep(10)
    print("continue...")
    #这行要加什么才能再回去执行上面的try?

while True:
     doSth()
     time.sleep(120)

try...except 语句里执行完 except, 怎么回去执行 try ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

你其实都已经想到用 while 了, 再往前进一步即可

以下是一个带最大重试次数的反复请求代码

# -*- coding: utf8 -*-
import time
import random

def dosomething():
    # 只有 1/3 随机概率执行到 print("hello")
    if random.randint(1, 3) == 3:
        print ("hello")
    else:
        raise Exception("unknown error")

def request_with_retry(max_times):
    times = 0
    while times <= max_times:
        times += 1
        try:
            dosomething()
            break
        except:
            time.sleep(1)
            print ("retry, times: %s/%s" % (times, max_times))
            
if __name__ == '__main__':
    request_with_retry(5)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...