异常后如何重试?

2024-03-29 00:25:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个以for i in range(0, 100)开头的循环。正常情况下,它运行正常,但有时由于网络状况而失败。目前,我已经设置了它,因此在失败时,它将continue在except子句中(继续下一个i的数字)。

我是否可以将同一个数字重新分配给i,并再次运行循环的失败迭代?


Tags: in网络for情况range数字状况except
3条回答

我更喜欢限制重试次数,这样,如果特定项目有问题,您最终将继续执行下一个项目,因此:

for i in range(100):
  for attempt in range(10):
    try:
      # do thing
    except:
      # perhaps reconnect, etc.
    else:
      break
  else:
    # we failed all the attempts - deal with the consequences.

retrying package是一种在失败时重试代码块的好方法。

例如:

@retry(wait_random_min=1000, wait_random_max=2000)
def wait_random_1_to_2_s():
    print("Randomly wait 1 to 2 seconds between retries")

在for循环中执行while True,将try代码放入其中,并且仅当代码成功时才从该while循环中断。

for i in range(0,100):
    while True:
        try:
            # do stuff
        except SomeSpecificException:
            continue
        break

相关问题 更多 >