【问题标题】:Is there a way to get a list of all pep8 violations using pycodestyle?有没有办法使用 pycodestyle 获取所有 pep8 违规的列表?
【发布时间】:2021-02-20 20:18:05
【问题描述】:

我想使用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 中的任何东西)获取列表的方法。我该怎么做?

我做了什么:我查看了谷歌,浏览了 pycodestyle 的文档,但没有提到任何内容。

【问题讨论】:

    标签: python pep8 pycodestyle


    【解决方案1】:

    通过浏览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']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-16
      • 2020-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      • 2020-01-17
      相关资源
      最近更新 更多