gpt4 book ai didi

python - Pylint:如何防止打印

转载 作者:行者123 更新时间:2023-11-28 22:11:54 28 4
gpt4 key购买 nike

当我使用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 消息...

如何阻止 pylint 的 print()

这个选项不起作用:

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

最佳答案

只有这样才能做好...是使用您的 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)

PyLint 在评估代码后将不再执行 print()

关于python - Pylint:如何防止打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55342760/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com