如何在Python中的exception后重试?

我有一个循环开始与for i in range(0, 100) 。 通常它运行正常,但有时由于networking条件而失败。 目前,我已经设置,以便在失败时,它将continue在除外条款(继续为i的下一个数字)。

我有可能重新分配相同的数字给i并再次运行循环失败的迭代?

在你的for循环里面做一段while True ,把你的try代码放在里面,只有当你的代码成功的时候, while循环才会中断。

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

我更喜欢限制重试的次数,所以如果这个特定的项目有问题,你最终会继续下一个,因此:

 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. 

重试包是在失败时重试代码块的好方法。

例如:

 @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" 

更“function”的方法,而不使用那些丑陋的while循环:

 def tryAgain(retries=0): if retries > 10: return try: # Do stuff except: retries+=1 tryAgain(retries) tryAgain() 

最明确的方法是明确地设置i 。 例如:

 i = 0 while i < 100: i += 1 try: # do stuff except MyException: continue 

这是一个类似于其他的解决scheme,但是如果它不能达到规定的数量或重试次数,将会引发exception。

 tries = 3 for i in range(tries): try: do_the_thing() except KeyError as e: if i < tries - 1: # i is zero indexed continue else: raise break 

带有超时的通用解决scheme:

 import time def onerror_retry(exception, callback, timeout=2, timedelta=.1): end_time = time.time() + timeout while True: try: yield callback break except exception: if time.time() > end_time: raise elif timedelta > 0: time.sleep(timedelta) 

用法:

 for retry in onerror_retry(SomeSpecificException, do_stuff): retry() 

Python修饰符库中有类似的东西。

请记住,它不testing例外,但返回值。 它重试,直到装饰函数返回True。

一个稍微修改版本应该做的伎俩。

使用recursion

 for i in range(100): def do(): try: ## Network related scripts except SpecificException as ex: do() do() ## invoke do() whenever required inside this loop 

使用while和counter:

 count = 1 while count <= 3: # try 3 times try: # do_the_logic() break except SomeSpecificException as e: # If trying 3rd time and still error?? # Just throw the error- we don't have anything to hide :) if count == 3: raise count += 1 

你可以使用Python重试包。 重试

它是用Python编写的,以简化向任何东西添加重试行为的任务。

这是我的想法如何解决这个问题:

 j = 19 def calc(y): global j try: j = j + 8 - y x = int(y/j) # this will eventually raise DIV/0 when j=0 print("i = ", str(y), " j = ", str(j), " x = ", str(x)) except: j = j + 1 # when the exception happens, increment "j" and retry calc(y) for i in range(50): calc(i) 

只有在try子句成功时才增加循环variables