如何通过pylint.run_pylint获取错误列表并存储到Python列表中?
如何通过Pylint获取错误并存储到列表中
直接使用pylint.run_pylint()无法直接捕获错误结果,因为它默认将输出打印到控制台。要收集错误到列表,需要通过自定义Reporter类来实现,具体步骤如下:
1. 自定义错误收集Reporter
继承pylint.reporters.BaseReporter类,重写handle_message方法来捕获每一条错误信息:
import pylint from pylint.reporters import BaseReporter from pylint.lint import pylinter class ErrorCollector(BaseReporter): def __init__(self): super().__init__() self.errors = [] # 用于存储所有错误的列表 def handle_message(self, msg): # 将错误的关键信息整理为字典,存入列表 error_detail = { "错误代码": msg.msg_id, "行号": msg.line, "列号": msg.column, "错误信息": msg.msg, "错误标识": msg.symbol, "文件路径": msg.path } self.errors.append(error_detail) # 以下两个方法是Reporter的必填实现,无需额外逻辑 def display_messages(self, layout): pass def display_reports(self, layout): pass
2. 使用自定义Reporter运行Pylint
创建Pylinter实例,挂载自定义的Reporter并执行检查:
# 初始化错误收集器 error_collector = ErrorCollector() # 配置Pylinter linter = pylinter.Pylinter() linter.load_default_plugins() linter.check(["my_code.py"]) linter.reporter = error_collector # 执行检查 linter.run() # 输出收集到的错误列表 for error in error_collector.errors: print(error)
执行后,error_collector.errors就是包含所有错误信息的列表,每个元素是一个记录错误详情的字典。
内容的提问来源于stack exchange,提问作者Bsh
相关产品推荐
相关产品推荐

