로 시작하는 루프가 for i in range(0, 100)있습니다. 일반적으로 올바르게 실행되지만 네트워크 상태로 인해 실패하는 경우가 있습니다. 현재 나는 실패 continue했을 때 except 절 에 있도록 설정했습니다 (에 대한 다음 숫자로 계속 i).
동일한 번호를 다시 할당 i하고 실패한 루프 반복을 다시 실행할 수 있습니까?
답변
를 수행 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")
답변
여기에 다른 솔루션과 유사한 솔루션이 있지만 규정 된 수 또는 재 시도에서 성공하지 못하면 예외가 발생합니다.
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
답변
추악한 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
답변
시간 초과가있는 일반적인 솔루션 :
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()
