减少计数值以重复循环是行不通的。 python 中的 for 循环有一个包含 continue 语句的异常处理程序

Reducing count value to repeat a loop cycle is not working. The for loop in python has an exception handler that has a continue statement

for i in range(0, 650):
    s = ticket[i]
    try:
        response = resource.get(path='ticket/%s' % s[0]) # Get ticket data from RT server
    except urllib2.URLError, e: # If connection fails
        resource = RTResource(url, user, pwd, CookieAuthenticator) # Reconnect to RT server
        count -= 1 # Count re-connection attempts
        if count < 0:
            print "Connection failed at ticket %s" % s[0]
            print "Got %s tickets out of %s" % {i + 1, len(ticket) + 1}
            wb.save(fname)
            sys.exit(1)
        print 'Trying again...'
        i -= 1
        continue
    count = 10
    ...more code here...

上面的代码执行得很好,但是在抛出异常时会跳过一次迭代。我试图减少 i 的值,然后继续循环,以便在抛出异常时,循环将重复 i 的相同值。当跳过 i 的值时,我会从 RT 服务器丢失一张票。我该如何解决?

(除了 g.d.d.c 提出的正确观点。关于无法按照您所走的特定方式递减循环计数器,)这类事情正是 finally 的动机。您可能应该按如下方式组织代码:

  • try - 应该 运行 但可能不会

  • 的部分
  • except - 只有出现问题时才要做的部分

  • else(可选)- 只有在没有问题时才要做的部分

  • finally - 无论如何都要做的事情

你...不能在 python 中这样做。您不能影响迭代器的值 - 它在循环中的每个步骤都使用它自己的内部值,而不注意您的覆盖尝试。如果你 每次迭代都成功,我使用这样的东西:

while True:
    # code here
    if success:
        break

并将其放入 for 循环中。或者更好的是,提取一个方法来简化可读性,但那是另一个 post.

按照 g.d.d.c 的建议,在 for 循环中嵌入 while 循环的替代方法是简单地使用 while 循环而不是 for 循环,如下所示:

i = 0
while i < 650:
    s = ticket[i]
    try:
        response = resource.get(path='ticket/%s' % s[0]) # Get ticket data from RT server
    except urllib2.URLError, e: # If connection fails
        resource = RTResource(url, user, pwd, CookieAuthenticator) # Reconnect to RT server
        count -= 1 # Count re-connection attempts
        if count < 0:
            print "Connection failed at ticket %s" % s[0]
            print "Got %s tickets out of %s" % {i + 1, len(ticket) + 1}
            wb.save(fname)
            sys.exit(1)
        print 'Trying again...'
        continue
    count = 10
    i += 1
    ...more code here...