pep8:Python代码风格检查工具
Python官网定义的代码风格 PEP 0008 – Style Guide for Python Code。
pep8是检测编码风格是否符合 PEP 0008 的工具。
安装pep8:
pip install pep8
升级pep8:
pip install --upgrade pep8
卸载pep8:
pip uninstall pep8
如果使用的是Ubuntu,还可以使用从apt仓库中安装:
$ sudo apt-get install pep8
###使用示例
故意写几行不符合Python编码风格的代码(test.py):
import sys, os
from subprocess import Popen, PIPE
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
检查是否符合编码规范:
$ pep8 --first test.py
test.py:1:11: E401 multiple imports on one line
test.py:4:1: E302 expected 2 blank lines, found 1
test.py:6:5: E125 continuation line with same indent as next logical line
1、4、6行代码不符合规范
你还可以输出不符合规范的代码和原因:
$ pep8 --show-source --show-pep8 test.py
更多选项,查看帮助信息:
$ pep8 -h
使用代码测试(CodeStyle.py):
import pep8
python_code_style_checker = pep8.Checker('test.py', show_source=True)
file_errors = python_code_style_checker.check_all()
print("Found %s errors (and warnings)" % file_errors)
Written on March 22, 2016