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 ?
回答:
你其实都已经想到用 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)
回答:
def loop(): times = 0
while True:
try:
do_something()
return
except:
times +=1
# 如果尝试次数达到10次就跳出循环
if times == 10:
print("尝试次数过多,失败")
return
回答:
你需要的可能不是try except,而是with ... as
以上是 try...except 语句里,执行完 except 怎么回去执行 try ? 的全部内容, 来源链接: utcz.com/a/161544.html