如果发生错误,请在循环中重复迭代

时间:2014-12-01 21:17:03

标签: python loops exception exception-handling iteration

是否有可以重复最近迭代的breakcontinue等命令?

例如,抛出异常时。

for i in range(0,500):
    try:
        conn = getConnection(url+str(i))
        doSomething(conn)
    except:
        repeat

让我们进行迭代,其中i变量的值为6。在此迭代期间,发生了一些连接错误。我想重复这个迭代。

是否有可以做到这一点的命令?

当然我可以这样做:

i=0
while i!=500:
    try:
        conn = getConnection(url+str(i))
        doSomething(conn)
        i+=1
    except:
        pass

5 个答案:

答案 0 :(得分:11)

不,没有命令"倒带" Python中的for循环。

您可以在for循环中使用while True:循环:

for i in range(500):
    while True:
        try:
            conn = getConnection(url+str(i))
            doSomething(conn)
        except Exception: # Replace Exception with something more specific.
            continue
        else:
            break

或没有else:

for i in range(500):
    while True:
        try:
            conn = getConnection(url+str(i))
            doSomething(conn)
            break
        except Exception: # Replace Exception with something more specific.
            continue

但我个人认为您提出的解决方案更好,因为它避免了缩进级别。

答案 1 :(得分:3)

for i in range(500):
    while True
        try:
            conn = getConnection(url+str(i))
            break
        except Exception: # still allows to quit with KeyboardInterrupt
            continue
    do_your_stuff()

这看起来有点风险,但是,您至少应该在while块中启用一些日志记录。

如果您希望在更多地方使用它,您可以编写一个简单的装饰器:

def keep_trying(fn, *args, **kwargs):
    def inner(*args, **kwargs):
        while True:
            try:
                return fn(*args, **kwargs)
            except Exception:
                continue
    return inner

# later you can use it simple like this:
for i in range(500):
    conn = keep_trying(getConnection)(url+str(i))

答案 2 :(得分:2)

您可以使用生成器:

def process_connections(n_connections, url, max_tries=50):
    i = 0
    try_count = 0
    while i < n_connections:
        try:
            conn = getConnection(url+str(i))
            yield conn
        except:
            try_count += 1
            if try_count > max_tries:
                raise Exception("Unable to connect after %s tries" % max_tries)
        else:
            i += 1 # increments only if no exception 

您执行操作:

for conn in process_connections(500, url):
    do_something(conn)

答案 3 :(得分:0)

为什么不使用if声明?

n=6
i=0
while i!=500:
    failed = False;
    try:
        conn = getConnection(url+str(i))
        doSomething(conn)
        i+=1
    except:
        #handle error
        failed = True;

    #try again if n-th case failed first time
    if(i == n and failed):
        try:
            conn = getConnection(url+str(i))
            doSomething(conn)
        except:
            #handle error

答案 4 :(得分:0)

您可以使用嵌套for循环来设置重试操作次数的上限。这是@ PierreAlex的生成器答案但不具备额外功能定义的sam。

for i in range(500):
    for retry in range(10):
        try:
            conn = getConnection(url+str(i))
            doSomething(conn)
        except Exception: # Replace Exception with something more specific.
            time.sleep(1)
    else:
        print "iteration", i, "failed"