对于我这种习惯了 Java 这种编译型语言,在使用 Python 这种动态语言的时候,发现错误经常只能在执行的时候发现,总感觉有点不放心。
而且有一些错误由于隐藏的比较深,只有特定逻辑才会触发,往往导致需要花很多时间才能将语法错误慢慢排查出来。其实有一些错误是很明显的,假如能在写程序的时候发现这些错误,就能提高工作效率。
这时候 Python 静态语法检查工具就出现了。
本文使用之前文章Python 助你填写高考志愿中的代码作为测试代码。另外有些输出过长的,进行了截取。
pep8/pycodestyle
相信大家多多少少都见过 PEP 8,那 PEP 8 到底是个啥?
其实 PEP 8 是一种 Python 代码规范指南,可以参阅官网:https://www.python.org/dev/peps/pep-0008/,其目的是为了保持代码的一致性、可读性。
检查自己代码是否符合 PEP 8 规范,一个简单的工具就是:pep8。
安装
$ pip install pep8
在使用时发现 pep8 给出了一个警告:
$ pep8 gkcx.py
/usr/local/lib/python3.5/dist-packages/pep8.py:2124: UserWarning:
pep8 has been renamed to pycodestyle (GitHub issue #466)
Use of the pep8 tool will be removed in a future release.
Please install and use `pycodestyle` instead.
$ pip install pycodestyle
$ pycodestyle ...
'\n\n'
意思是 pep8 已被 pycodestyle 替代!
使用
基本使用方法:$ pycodestyle [file name or directory name]
$ pycodestyle gkcx.py
gkcx.py:11:80: E501 line too long (135 > 79 characters)
gkcx.py:14:1: E302 expected 2 blank lines, found 1
gkcx.py:15:80: E501 line too long (94 > 79 characters)
...省略部分
gkcx.py:67:1: E305 expected 2 blank lines after class or function definition, found 1
gkcx.py:71:80: E501 line too long (100 > 79 characters)
gkcx.py:82:25: E231 missing whitespace after ','
gkcx.py:82:29: E231 missing whitespace after ','
gkcx.py:84:1: W293 blank line contains whitespace
gkcx.py:84:1: W391 blank line at end of file
- 参数
--statistics -qq
:对结果进行汇总
$ pycodestyle gkcx.py --statistics -qq
3 E203 whitespace before ':'
1 E225 missing whitespace around operator
16 E231 missing whitespace after ':'
3 E302 expected 2 blank lines, found 1
1 E305 expected 2 blank lines after class or functi