如何修改Python代码输出devices.txt中未匹配Hosts列表的主机?
修改Python代码筛选未匹配Hosts前缀的生产级主机
修改思路
原代码是筛选匹配Hosts列表中任一前缀且属于Production/Production-Secondary级别的主机,现在需要反转匹配逻辑:筛选不匹配Hosts列表中任何前缀且级别符合要求的主机。
具体修改点
- 替换Host前缀匹配逻辑:将“判断是否存在匹配的Host前缀”改为“判断是否不存在任何匹配的Host前缀”,用
not any(device.startswith(host) for host in Hosts)实现,比循环判断更简洁高效。 - 优化换行处理:原代码用
row.rsplit('\n')获取行内容,直接改用row.strip()去除换行符和首尾空白,代码更简洁。 - 重命名函数:将
list改为list_devices,避免和Python内置函数list重名引发潜在冲突。
修改后的完整代码
import re Hosts = ["gvff", "etc"] def list_devices(): with open('C:/Users/user/Desktop/scripts/devices.txt', 'r') as file: for row in file: line_content = row.strip() devices = re.search("^(.*?)\,(.*?)\,(.*?)\,", line_content) if devices is not None: device = devices.group(1) hardwaretype = devices.group(2) level = devices.group(3) # 筛选条件:级别符合要求,且不匹配Hosts中的任何前缀 if level in ('Production', 'Production-Secondary') and not any(device.startswith(host) for host in Hosts): print(f'| {device} | {hardwaretype} | {level} |') list_devices()
关键逻辑说明
not any(device.startswith(host) for host in Hosts):遍历Hosts列表,仅当设备名不以列表中任何前缀开头时,条件成立。level in ('Production', 'Production-Secondary'):用元组判断替代原有的两次等于判断,代码更简洁易维护。
内容的提问来源于stack exchange,提问作者joshi1999
相关产品推荐
相关产品推荐

