Search code examples
pythonpython-3.xpylint

Pylint: how to prevent prints


When i use pylint:

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

My messages variable has the correct informations as JSON. However, pylint prints the JSON message in the console...

How can i prevent print() of pylint ?

This option doesn't work:

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

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


Solution

  • The only way to do it well... is to use your ReporterClass.

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

    The code below has the same behavior as json but its display_messages method does nothing

    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)
    

    PyLint will no longer do print() after evaluating the code.