首页 > 解决方案 > Pylint:如何防止打印

问题描述

当我使用 pylint 时:

import pylint.lint
options = [
    filename, 
    "--output-format=json"
]
results = pylint.lint.Run(options, do_exit=False)
messages = results.linter.reporter.messages

我的messages变量具有正确的信息,如JSON. 但是,pylint 在控制台中打印JSON消息...

我怎样才能防止print()pylint ?

此选项不起作用:

options = [
    filename, 
    "--output-format=json",
    "--reports=no"    # Tells whether to display a full report or only the messages.
]

https://pylint.readthedocs.io/en/stable/technical_reference/features.html#reports-options

标签: pythonpython-3.xpylint

解决方案


做好它的唯一方法......是使用你的ReporterClass.

import pylint.lint
options = [
    filename, 
    "--output-format=mypackage.mymodule.MyReporterClass" 
]
results = pylint.lint.Run(options, do_exit=False)
messages = results.linter.reporter.messages

下面的代码具有相同的行为,json但它的display_messages方法什么也不做

import html
from pylint.interfaces import IReporter
from pylint.reporters import *

class MyReporterClass(BaseReporter):
    """Report messages and layouts."""

    __implements__ = IReporter
    name = "myreporter"
    extension = "myreporter"

    def __init__(self, output=sys.stdout):
        BaseReporter.__init__(self, output)
        self.messages = []

    def handle_message(self, msg):
        """Manage message of different type and in the context of path."""
        self.messages.append(
            {
                "type": msg.category,
                "module": msg.module,
                "obj": msg.obj,
                "line": msg.line,
                "column": msg.column,
                "path": msg.path,
                "symbol": msg.symbol,
                "message": html.escape(msg.msg or "", quote=False),
                "message-id": msg.msg_id,
            }
        )

    def display_messages(self, layout):
        """Do nothing."""

    def display_reports(self, layout):
        """Do nothing."""

    def _display(self, layout):
        """Do nothing."""


def register(linter):
    """Register the reporter classes with the linter."""
    linter.register_reporter(MyReporterClass)

print()PyLint在评估代码后将不再执行此操作。


推荐阅读