Python搜索日志字符串列表时循环首次迭代后终止问题排查
问题原因
现有函数无法完成全量日志条目校验,是3个核心逻辑错误导致的:
- 匹配到第一个关键词就直接执行
return,函数直接终止,后续所有关键词都不会被校验 - Python中打开的文件对象是单向迭代器,第一次遍历完所有日志行后,后续遍历会直接从文件末尾开始,读不到任何内容
- 第一个关键词的内层遍历结束后就直接执行
return False,根本不会进入后续关键词的校验循环 - 额外逻辑问题:
return True, print("fine")会返回元组(True, None),print函数本身没有返回值,写在return语句中属于无效逻辑
修复后代码
修复思路:先一次性读取所有日志行到内存,逐个校验所有关键词并记录缺失项,全部校验完成后再统一返回结果,同时输出对应提示。
def isClassDomainPassed(): with open(NR_log, 'r') as logfile: # 一次性读取所有日志行,避免文件迭代器单次遍历后失效 log_content = logfile.readlines() key1 = 'The application is in Class Domain tab' key2 = 'Inspection Sampling is open' key3 = 'Golden Image was chosen' key4 = 'Accurate Navigation was chosen' key5 = 'Golden Image is enabled with Accurate Navigation' key6 = 'Location was added to Inspection Locations List' key7 = 'All dies were added to Inspection Dies List' keys = [key1, key2, key3, key4, key5, key6, key7] missing_logs = [] for key in keys: found = False for line in log_content: if key in line: found = True break if not found: missing_logs.append(key) if len(missing_logs) == 0: print("所有日志条目校验通过") return True else: print(f"校验未通过,缺失以下日志条目:{missing_logs}") return False isClassDomainPassed()
可选优化
如果你的日志文件体积特别大,不想一次性把所有内容加载到内存,可以在每轮关键词校验前把文件指针重置到文件开头,修改后写法如下:
def isClassDomainPassed(): with open(NR_log, 'r') as logfile: key1 = 'The application is in Class Domain tab' key2 = 'Inspection Sampling is open' key3 = 'Golden Image was chosen' key4 = 'Accurate Navigation was chosen' key5 = 'Golden Image is enabled with Accurate Navigation' key6 = 'Location was added to Inspection Locations List' key7 = 'All dies were added to Inspection Dies List' keys = [key1, key2, key3, key4, key5, key6, key7] missing_logs = [] for key in keys: # 重置文件指针到开头,重新遍历文件 logfile.seek(0) found = False for line in logfile: if key in line: found = True break if not found: missing_logs.append(key) if len(missing_logs) == 0: print("所有日志条目校验通过") return True else: print(f"校验未通过,缺失以下日志条目:{missing_logs}") return False isClassDomainPassed()
内容的提问来源于stack exchange,提问作者I'm not a robot
相关产品推荐
相关产品推荐

