有没有办法使用pycodestyle获取所有pep8违规的列表?

问题描述

我想使用pycodestyle检查文件。我尝试使用their docs所说的话:

import pycodestyle

fchecker = pycodestyle.Checker('testsuite/E27.py')
file_errors = fchecker.check_all()
# I took off the show_source=True and the final print

显示错误,但是file_errors错误数,而不是错误本身。我希望将错误返回到列表中。如何使用pycodestyle做到这一点?

更多详细信息

pycodestyle一个根据PEP8准则检查代码的模块。通常,它与命令行一起使用,但是我想通过将其放入脚本来使其自动化。使用the docs,您将得到:

import pycodestyle

fchecker = pycodestyle.Checker('testsuite/E27.py',show_source=True)
file_errors = fchecker.check_all()

print("Found %s errors (and warnings)" % file_errors)

这将打印错误错误总数。但是,file_errors不是列表,而是错误数量

我想要一种从pycodestyle.Checker(或pycodestyle中的任何东西)获取列表的方法。我该怎么办?

我做过的事情:我看过Google,浏览了pycodestyle的文档,但没有提及。

解决方法

从略过source code开始,似乎没有任何办法可以返回错误,只需打印它们即可。因此您可以改为capture its stdout

from contextlib import redirect_stdout
import io

f = io.StringIO()  # Dummy file
with redirect_stdout(f):
    file_errors = fchecker.check_all()
out = f.getvalue().splitlines()  # Get list of lines from the dummy file

print(file_errors,out)

此代码基于ForeverWintranswer

例如,在这样的文件上运行它:

s  = 0

输出:

1 ['tmp.py:1:2: E221 multiple spaces before operator']