43

我想调用 Pylint 检查器,仅限于错误信号部分,作为我的单元测试的一部分。所以我检查了 Pylint 可执行脚本,进入了pylint.lint.Run辅助类,然后我迷失在一个很长的__init__函数中,最后调用sys.exit().

有没有人尝试过并设法做到这一点?

梦想计划是这样的:

if __name__ == '__main__':
  import pylint.lint
  pylint.lint.something(__file__, justerrors=True)
  # now continue with unit testing

有什么提示吗?除了“复制__init__方法并跳过sys.exit()”之外,我的意思是?

我不需要Pylint 运行测试,它也可能是pyflakes其他软件:随意提出替代方案。

4

8 回答 8

34

查看pylint/epylint.py包含两种不同方式以编程方式启动 Pylint 的文件。

您也可以简单地调用

from pylint.lint import Run
Run(['--errors-only', 'myfile.py'])

例如。

于 2010-01-14T07:03:31.433 回答
22

我最近遇到了同样的问题。syt 是对的,pylint.epylint那里有几种方法。但是,它们都调用了一个子进程,在该子进程中再次启动了 python。就我而言,这变得非常缓慢。

从 mcarans 答案构建,发现有一个标志出口,我做了以下

class WritableObject(object):
    "dummy output stream for pylint"
    def __init__(self):
        self.content = []
    def write(self, st):
        "dummy write"
        self.content.append(st)
    def read(self):
        "dummy read"
        return self.content
def run_pylint(filename):
    "run pylint on the given file"
    from pylint import lint
    from pylint.reporters.text import TextReporter
    ARGS = ["-r","n", "--rcfile=rcpylint"]  # put your own here
    pylint_output = WritableObject()
    lint.Run([filename]+ARGS, reporter=TextReporter(pylint_output), exit=False)
    for l in pylint_output.read():
        do what ever you want with l...

在我的情况下,这大约快 3 倍。有了这个,我已经完成了一个完整的项目,使用完整的输出来检查每个源文件,指出错误,并从他们的注释中对所有文件进行排名。

于 2011-10-27T17:06:39.383 回答
4

我们可以使用 StringIO,而不是创建 WritableObject 类。StringIO 包含 write 方法。

import sys
try:
    from io import StringIO
except:
    from StringIO import StringIO

stdout = sys.stdout
sys.stdout = StringIO()

ARGS = ["-r","n", "--rcfile=rcpylint"]
r = lint.Run(['../test.py']+ARGS, exit=False)

test = sys.stdout.getvalue()
sys.stdout.close()
sys.stdout = stdout

print (test.split('\n'))

来源:

于 2016-03-31T12:41:38.970 回答
3

我很高兴我遇到了这个。我在这里使用了一些答案并提出了一些倡议:

# a simple class with a write method
class WritableObject:
    def __init__(self):
        self.content = []
    def write(self, string):
        self.content.append(string)
pylint_output = WritableObject()

pylint = lint.Run(args, reporter=ParseableTextReporter(pylint_output), exit=False)

上面的 Args 是一个字符串列表,例如。[“-r”,“n”,“myfile.py”]

于 2011-01-26T10:27:01.970 回答
2

注意:在某些时候pylint更改了界面。上面的例子需要替换exit=Falsedo_exit=False. (@mad7777,@amit-tripathi)

(根据https://github.com/carsongee/pytest-pylint/issues/80学习)

于 2019-06-07T18:00:03.240 回答
2

这是我用来以编程方式调用 pylint 的包装器,因此我有一个 --fail-under arg 来覆盖默认的 pylint 退出代码(对 CI 很有用)。此代码段已使用 pylint 2.3.1 进行了测试

""" Execute pylint and fail if score not reached. """
import argparse
import sys
from pylint import lint

desc = "PyLint wrapper that add the --fail-under option."\
       " All other arguments are passed to pylint."
parser = argparse.ArgumentParser(description=desc, allow_abbrev=False)
parser.add_argument('--fail-under', dest='threshold', type=float, default=8,
                    help='If the final score is more than THRESHOLD, exit with'
                    ' exitcode 0, and pylint\'s exitcode otherwise.')

args, remaining_args = parser.parse_known_args()

threshold = args.threshold

run = lint.Run(remaining_args, do_exit=False)
score = run.linter.stats['global_note']

if score < threshold:
    sys.exit(run.linter.msg_status)
于 2019-09-22T12:43:12.040 回答
0

pylint 的另一个入口点是epylint.py_run实现 stdout 和 stderr 拦截的函数。但是,如下代码所示,pylint 似乎没有将其报告写入 stdout:

from pylint import epylint

pylint_stdout, pylint_stderr = epylint.py_run(__file__, return_std=True)
print(pylint_stdout.getvalue())  # -> there is just the final rank, no report nor message
print(pylint_stderr.getvalue())

现在,我发现来自 API 的 pylint 和来自 CLI 的 pylint 不使用相同的默认参数。因此,您只需提供 pylint 所需的参数即可。

from pylint import epylint
options = '--enable=all'  # all messages will be shown
options += '--reports=y'  # also print the reports (ascii tables at the end)

pylint_stdout, pylint_stderr = epylint.py_run(__file__ + ' ' + options, return_std=True)
print(pylint_stdout.getvalue())
print(pylint_stderr.getvalue())

如此处所述,pylint 将自行执行解析,并将在 stdout 中正确输出预期结果。

于 2017-06-29T13:01:06.293 回答
0

正如这里的其他答案所提到的,pylint.lint.Run这是要走的路,但是,没有很好的 Python 3 特定用途的演示。此外,还pylint提供了一个有用的报告器类,应该用于捕获 pylint 运行的输出。所有不同的输出类型都有选项。在以下示例中,我将使用ColorizedTextReporter该类捕获 Colorized 输出。

从 pylint 2.12 开始

from pylint import lint
from pylint.reporters import text

# list of pylint args to only enable warnings, errors, and fatals
args = ["my_file.py", "--enable=W,E,F"]

pylint_output = StringIO() # need a StringIO object where the output will be stored
reporter = text.ColorizedTextReporter(pylint_output)

run = lint.Run(args, reporter=reporter, exit=False) # exit=False means don't exit when the run is over

score = run.lint.stats.global_note # pylint score out of 10

# also available are stats.error, stats.warnings, etc...

在 pylint 2.12 之前

唯一的区别是stats对象Run().lint是字典。所以你会得到分数run.lint.stats.get("global_note")

于 2021-12-06T20:26:03.843 回答