【问题标题】:Continuing to the next iteration in a For loop after an exception is found using Python在使用 Python 发现异常后继续进行 For 循环中的下一次迭代
【发布时间】:2019-03-21 06:19:23
【问题描述】:

我在一个函数中有一个 For 循环,它遍历 3 个不同的列表。但是,代码中的某个点可能会发生异常。我想要做的是在达到那个例外之后。我希望它跳到下一次迭代并再次通过 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

【问题讨论】:

  • 现在它并没有像你说的那样做(如果你捕捉到那个特定的异常,for循环将继续)。也许您省略的某些代码是问题所在?
  • 您好,循环结束时不需要继续,因为没有任何代码可以跳过。您是否发现了正确的异常?
  • 请用我们可以实际运行的代码构造一个minimal reproducible example。这里的实际问题让人分心。乍一看,我不明白为什么捕获异常应该结束你的函数。但是如果没有可以自行运行并演示问题的代码,我无法告诉您更多信息。
  • 谢谢大家的帮助。当我将脚本分解为更易于管理的视图时,我能够解决问题

标签: python function for-loop continue except


【解决方案1】:

我猜你必须声明一个变量是否应该跳过迭代(如果我理解你想要做什么):

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 2021-06-01
    • 1970-01-01
    • 2023-01-13
    相关资源
    最近更新 更多