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

Is there a way to get a list of all pep8 violations using pycodestyle?

我想使用 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 guidelines. Usually, it is used with the command line, but I want to automate it by putting it into a script. Using 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, it doesn't seem to have any way to return the errors, just print them. So you can 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)

此代码基于ForeverWintr's answer

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

s  = 0

输出:

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