Store Python PEP8 module output

偶尔善良 提交于 2019-12-04 22:24:31

There are at least two ways to do this. The simplest is to redirect sys.stdout to a text file, then read the file at your leisure:

import pep8
import sys

saved_stdout = sys.stdout
sys.stdout = open('pep8.out', 'w')

pep8_checker = pep8.StyleGuide(format='pylint')
pep8_checker.check_files(paths=['./test.py'])
r = pep8_checker.check_files(paths=['./test.py'])

sys.stdout.close()
sys.stdout = saved_stdout

# Now you can read "pep.out" into a variable

Alternatively you can write to a variable using StringIO:

import pep8
import sys

# The module name changed between python 2 and 3
if sys.version_info.major == 2:
    from StringIO import StringIO
else:
    from io import StringIO

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

pep8_checker = pep8.StyleGuide(format='pylint')

pep8_checker.check_files(paths=['./test.py'])
r = pep8_checker.check_files(paths=['./test.py'])

testout = sys.stdout.getvalue()
sys.stdout.close()
sys.stdout = saved_stdout

# testout contains the output.  You might wish to testout.spilt("\n")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!