Python 常用静态代码检查工具简介

对于我这种习惯了 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
  • 2
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值