Search code examples
pythonpython-3.xpylint

How to get the list of errors from pylint?


I have a Python script called my_code.py. I am using:

import pylint

pylint.run_pylint(argv=["my_code.py"])

How to get all errors and store them in a list in the above snippet?


Solution

  • Inspired by this answer, one way is to get the json report and iterate through it.

    import json
    from io import StringIO
    from pylint.lint import Run
    from pylint.reporters import JSONReporter
    
    reporter = StringIO()
    Run(["my_code.py"], reporter=JSONReporter(reporter), do_exit=False)
    results = json.loads(reporter.getvalue())
    errors = {}
    for i in results:
        errors[i.get('message-id')] = i.get('message')
    
    for k, v in errors.items():
        print(k, v)
    

    This will print each error code and the corresponding message.

    For example, if you have my_code.py as follows:

    def foo(l: List[int]) -> List[int]:
        return l[1:]
    
    

    then after running my solution, you will get:

    C0304 Final newline missing
    C0114 Missing module docstring
    C0116 Missing function or method docstring
    C0104 Disallowed name "foo"
    C0103 Argument name "l" doesn't conform to snake_case naming style
    E0602 Undefined variable 'List'