Flake8:如何将选项传递给旧版API?

时间:2019-03-13 17:25:52

标签: python flake8

我正在使用flake8旧版API在某些文件上运行样式检查器,代码如下:

from flake8.api import legacy
def check_style_func(filename):
    style_guide = legacy.get_style_guide()
    report = style_guide.check_files([filename])
    if report.total_errors == 0:
        # do something and return
    else:
       # do another thing and return

问题是所有错误都将在stdout中打印出来并与程序输出混合在一起,是否有办法将“ --output-file = FILE”传递给flake8的api版本?

get_style_guide函数具有**kwargs参数,我已经尝试调用get_style_guide(output_file='file.txt')get_style_guide(options='--output-file=file.txt'),但是没有用。

2 个答案:

答案 0 :(得分:0)

这并不是您想要的,但是传递Cannot resolve symbol 'var'对我来说可以使输出静音。现在,我只是想访问那些似乎存储在quiet=3中的数据(但这是一个私有API)。

答案 1 :(得分:0)

我刚刚找到了一种解决方法:redirect_stdout

from flake8.api import legacy
import io
from contextlib import redirect_stdout

def check_style_func(filename):
    with io.StringIO as out, redirect_stdout(out):
         style_guide = legacy.get_style_guide()
         report = style_guide.check_files([filename])
         flake8output = out.getvalue()
    if report.total_errors == 0:
        # do something and return
    else:
       # do another thing and return

解决方案是在flake8执行期间打开缓冲区并将stdout重定向到缓冲区,然后将缓冲区内容存储在变量中,以便稍后写入文件。