Python多循环导致配置重复问题求解
配置文件脚本重复项问题解决
问题说明
需要编写脚本根据用户输入的设备数量生成对应端口配置:每个端口对应唯一的连接描述(端口号从3开始,连接编号从2开始),但当前代码生成了大量重复配置,需修正。
尝试代码
import os import sys a=int(input('How many devices will there be?: ')) q=input('What is the site code?') with open(f'device.{q}.txt', 'w') as f: for ports in range(3, a + 3): for lag in range(2, a + 2): f.write(f'set interface x/x/p{ports} user-label "Connection Link to device.{q} : Connection -{lag}"\n\n') f.close()
当前错误输出(含冗余项)
set interface x/x/p3 user-label "Connection Link to device.device - Desc: Connection-2" set interface x/x/p3 user-label "Connection Link to device.device - Desc: Connection-3" # 不需要此项 set interface x/x/p4 user-label "Connection Link to device.device - Desc: Connection-2" # 不需要此项 set interface x/x/p4 user-label "Connection Link to device.device - Desc: Connection-3"
期望输出
set interface x/x/p3 user-label "Connection Link to device.device - Desc: Connection-2" set interface x/x/p4 user-label "Connection Link to device.device - Desc: Connection-3"
解决方案
问题根源是嵌套循环产生了笛卡尔积:每个端口号会遍历所有连接编号,导致重复配置。只需让端口号和连接编号一一对应,用单循环即可实现:
修正后代码
import os import sys device_count = int(input('How many devices will there be?: ')) site_code = input('What is the site code?') with open(f'device.{site_code}.txt', 'w') as f: # 遍历索引,同时计算对应的端口号和连接编号 for i in range(device_count): port_num = 3 + i lag_num = 2 + i f.write(f'set interface x/x/p{port_num} user-label "Connection Link to device.{site_code} : Connection -{lag_num}"\n') # with语句会自动关闭文件,无需手动调用f.close()
说明
- 去掉嵌套循环,用单循环遍历设备数量次
- 每次循环中,端口号从3开始递增,连接编号从2开始递增,保证一一对应
with语句会自动管理文件资源,无需手动关闭文件
内容的提问来源于stack exchange,提问作者Lambo_Italia
相关产品推荐
相关产品推荐

