Python网络自动化脚本如何让打印内容与设备名处于同一行
问题根因
使用readlines()方法读取文本文件时,除文件最后一行外,其余读取到的内容末尾都会自带换行符\n。打印输出时这个换行符会被触发执行,因此出现设备名和后续日志内容被拆分到两行的问题,最后一行无换行符所以输出格式符合预期。
修复方案
只需在读取到设备名后去除末尾的空白字符即可,该操作会自动移除换行符、首尾多余空格/制表符,不会影响用户正常粘贴设备列表的使用体验。
将代码中的host = host替换为:
host = host.strip()
修正后的核心代码
with open('devices.txt', 'r') as routers: contents = routers.readlines() for host in contents: #for device_type in device_types: global hostname u = 'autouser-netmri' p = 'tRB66J2S' # 去除行尾换行符和首尾空白字符 host = host.strip() cisco = { 'device_type': 'cisco_ios', 'host': host, 'username': 'autouser-netmri',#u, # ssh username 'password': 'tRB66J2S',#p, # ssh password } now = datetime.now() logs_time = now.strftime("%H:%M:%S") print("" + logs_time + ": " + host + " Checking this device for available space ")
内容的提问来源于stack exchange,提问作者Steve
相关产品推荐
相关产品推荐

