如何在Python中实现readA向readB传递Devices变量
如何将readA函数中的Devices变量传递给readB函数?
你当前的代码里,readB函数直接引用了Devices变量,但这个变量只在readA的参数作用域内,readB无法直接访问,会触发NameError。解决这个问题最直接的方式是给readB增加一个参数,把Devices作为参数传递进去,具体修改如下:
修改后的完整代码
def readB(x, Devices): # 改用with语句管理文件,避免手动关闭的遗漏 with open(f'C:/Users/DotNet/Downloads/Backup Configurtion files Test/{Devices}-NO trust upstream default77.txt', "a") as rr: with open(f'C:/Users/DotNet/Downloads/Backup Configurtion files Test/{Devices}.cfg') as resultFile: for line in resultFile: if x in line: tt = next(resultFile) UU = next(resultFile) CC = next(resultFile) EE = next(resultFile) FF = next(resultFile) if "interface " in UU: rr.write(x + '\n' + tt) elif "interface " in CC: rr.write(x + '\n' + tt + UU) elif "interface " in EE: rr.write(x + '\n' + tt + UU + CC) elif "interface " in FF: rr.write(x + '\n' + tt + UU + CC + EE) else: rr.write(x + '\n' + tt + UU + CC + EE + FF) break def readA(Devices): with open(f'C:/Users/DotNet/Downloads/Backup Configurtion files Test/{Devices}-NO trust upstream default88.txt') as bondNumberFile: for line in bondNumberFile: # 调用readB时传入Devices参数 readB(line.rstrip(), Devices) readA('10.0.130.30') readA('10.0.130.20')
关键改动说明
- 修改readB的参数列表:新增
Devices参数,让函数可以接收外部传入的设备标识 - 在readA中调用readB时传递Devices:每次循环调用
readB时,把当前的Devices变量传进去 - 优化文件操作:将原本直接
open的文件改为with语句管理,确保文件自动关闭,避免资源泄漏 - 简化路径写法:使用f-string替代字符串拼接,让路径代码更易读
这样每次调用readA传入不同的设备IP时,readB都能拿到对应的Devices值,生成正确的文件路径并处理内容。
内容的提问来源于stack exchange,提问作者Ahmed Shouaib
相关产品推荐
相关产品推荐

