You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 08:35:09