使用Python找到异常后,继续进行For循环中的下一个迭代

时间:2018-10-16 16:34:30

标签: python function for-loop continue except

我在一个遍历3个不同列表的函数中有一个For循环。在代码规范内的某个点可能会发生异常。我想要做的是在达到该异常之后。我希望它跳到下一个迭代并再次通过for循环。问题是当我捕获到异常时,它将终止整个功能,并且不会移至列表中的下一项。我不确定目前缺少什么。请参见下面的代码。谢谢

def config_backup(host_device,password_list,site_slug):
    for h,p,s in zip(host_device,password_list,site_slug):
        try:
            host = h
            password = p
            slug = s
            # ssh into device (exception occurs here)
            # do other stuff
        except NetMikoTimeoutException:
           print("[%s] is not reachable from site: %s " % (host, slug))
        continue

1 个答案:

答案 0 :(得分:0)

我想您必须声明一个变量是否应跳过迭代(如果我理解您要执行的操作):

def config_backup(host_device, password_list, site_slug):
    skipnext = False
    for host, password, slug in zip(host_device, password_list, site_slug):
        if skipnext: 
             skipnext = False
             continue
        try:
            # ssh into device (exception occurs here)
            # do other stuff
        except NetMikoTimeoutException:
           print("[%s] is not reachable from site: %s " % (host, slug))
           skipnext = True
        #continue #continue at the end does nothing