9

给你的代码跑个分?pylint使用教程

 4 years ago
source link: https://jiajunhuang.com/articles/2020_03_12-pylint.md.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

给你的代码跑个分?pylint使用教程

之前我一直使用 flake8 来检查Python项目中的代码规范,工作良好,除了一个问题,由于Python是动态语言,编译器只能做最基本 最简单的错误检查,这也就意味着,很多错误,如果肉眼看不出来,那就得等执行报错了才会被发现。

因此有必要使用 pylint 这种代码检查器来减少出错的概率。

各Linux发行版可以直接安装:

$ sudo apt install pylint

不过如果是使用了虚拟环境例如 pyenv, venv, virtualenv 等,还是建议在当前环境中直接安装:

$ pip install pylint

pylint 默认的输出有一些可能不适用于我们的项目,因此要有一个配置文件来进行配置,编辑 ~/.pylintrc

[FORMAT]
max-line-length=120
[MESSAGES CONTROL]
disable=C0114,C0116,C0103,W0703,C0115,R0201,R0914,R0903,R0913,R0801

比如上面的配置文件,就是说代码超过120个字符才会报代码过长,然后下面 MESSAGES CONTROL 中禁用的错误/警告类型就不会报错。 而这些错误警告码呢,就是自己来定制的,我是从 pylint <项目文件夹或代码文件> 的结果中抄出来的,比如:

hello = 1

在没有配置文件的情况下运行一下:

$ pylint hello.py 
************* Module hello
hello.py:2:5: C0326: Exactly one space required around assignment
world=2
     ^ (bad-whitespace)
hello.py:1:0: C0114: Missing module docstring (missing-module-docstring)
hello.py:1:0: C0103: Constant name "hello" doesn't conform to UPPER_CASE naming style (invalid-name)
hello.py:2:0: C0103: Constant name "world" doesn't conform to UPPER_CASE naming style (invalid-name)

----------------------------------------------------------------------
Your code has been rated at -10.00/10 (previous run: -10.00/10, +0.00)

有一些提示就不是特别适用,比如 C0114: Missing module docstring (missing-module-docstring), 于是把 C0114 加到 disable= 后面,再次运行:

$ pylint hello.py 
************* Module hello
hello.py:2:5: C0326: Exactly one space required around assignment
world=2
     ^ (bad-whitespace)

------------------------------------------------------------------
Your code has been rated at 5.00/10 (previous run: 5.00/10, +0.00)

不过我们不能每次都依靠跑一遍命令来检查错误,这种模式比较适用于CI,我们希望在编辑代码的时候就看到提示,不过这 一点也不难,比如vim,我使用 ale 这个插件,他默认如果检测到 pylint 就会使用 pylint 来检查

这个时候就好很多。注意 pylint 的输出里,最后会给你的代码评一个分,比如我维护的一个系统,在改之前是9.5分, 照着pylint给出的建议,改成了10分,你的呢?


微信公众号
关注公众号,获得及时更新

Ubuntu 18.04 dhcp更换新IP

Python中的新式类(new style class)和老式类(old style class)

Python Requests 简明教程

密码技术简明教程(三):证书和TLS

密码技术简明教程(二):散列、消息认证码和数字签名

SEO学习笔记

密码技术简明教程(一):对称加密和非对称加密

Kubernetes 笔记

go mod 和 logrus 路径大小写的问题

Flask自动加载Blueprint

在KVM里安装Minikube

搞定面试中的系统设计题

Crontab + Sendmail实现定时任务并且通知

Nginx设置Referer来防止盗图

Graphviz dot简明教程




About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK