You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python脚本报错‘continue未正确处于循环中’问题求助

问题解决:continue未处于循环中的错误修复

错误原因

你的代码核心问题是**try-except代码块没有放在for循环内部**,导致continue语句不在任何循环范围内,这就是IDE报错的原因。原代码中for循环仅完成了ios_device字典的定义就结束了,后续的设备连接、配置操作都在循环外部执行,既无法遍历所有设备,也不能通过continue跳过异常设备。

修正后的代码

将try-except整体缩进,放入for循环内部,同时优化日志写入模式(避免覆盖历史日志)、添加连接关闭操作、细化异常捕获:

from getpass import getpass
from netmiko import ConnectHandler
from netmiko.exceptions import NetMikoAuthenticationException, NetMikoTimeoutException
import time
import traceback

username = input('Username:')
password = getpass()

with open('commands_file') as f:
    commands_list = f.read().splitlines()

with open('device_file') as f:
    devices_list = f.read().splitlines()

# 用追加模式打开日志文件,避免覆盖历史记录
with open("exception_log.txt", "a") as log:
    for devices in devices_list:
        print(f'Connecting to device {devices}')
        device_ip = devices
        ios_device = {
            'device_type': 'cisco_ios',
            'ip': device_ip,
            'username': username,
            'password': password
        }

        try:
            net_connect = ConnectHandler(**ios_device)
            # 保存配置
            net_connect.save_config()
            time.sleep(5)
            # 执行重载倒计时
            output = net_connect.send_command_timing("reload in 10")
            if 'Proceed with reload?' in output:
                output += net_connect.send_command_timing("y")
            print(output)
            # 发送配置命令
            output = net_connect.send_config_set(commands_list)
            print(output)
            time.sleep(15)
            # 关闭设备连接
            net_connect.disconnect()
        # 捕获NetMiko相关的具体异常,避免捕获所有异常
        except NetMikoAuthenticationException:
            print(f"设备 {devices} 认证失败")
            traceback.print_exc(file=log)
            time.sleep(15)
            continue
        except NetMikoTimeoutException:
            print(f"设备 {devices} 连接超时")
            traceback.print_exc(file=log)
            time.sleep(15)
            continue
        except Exception as e:
            print(f"设备 {devices} 发生未知异常: {str(e)}")
            traceback.print_exc(file=log)
            time.sleep(15)
            continue

关键修改点说明

  • 将try-except块缩进至for循环内部,确保每次处理单个设备时,异常发生后continue能跳过当前设备,继续处理下一个
  • 日志文件改用a(追加)模式,避免每次运行脚本清空之前的异常记录
  • 捕获具体的NetMiko异常类型,便于精准定位问题(认证失败/连接超时),同时保留通用异常捕获兜底
  • 添加net_connect.disconnect()确保每次处理完设备后正常关闭连接,避免资源占用

内容的提问来源于stack exchange,提问作者ccsmooth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 18:30:58