需求背景:
Pylint 是一個(gè) Python 代碼分析工具,它分析 Python 代碼中的錯(cuò)誤穴张,查找不符合代碼風(fēng)格標(biāo)準(zhǔn)和有潛在問(wèn)題的代碼俊柔。
Pylint 是一個(gè) Python 工具埠况,除了平常代碼分析工具的作用之外,它提供了更多的功能:如檢查一行代碼的長(zhǎng)度痴怨,變量名是否符合命名標(biāo)準(zhǔn),一個(gè)聲明過(guò)的接口是否被真正實(shí)現(xiàn)等等器予。
Pylint 的一個(gè)很大的好處是它的高可配置性浪藻,高可定制性,并且可以很容易寫小插件來(lái)添加功能乾翔。
項(xiàng)目中需要做代碼規(guī)范檢查爱葵,所以研究一下pylint的使用。
pylint使用:
-
安裝pylint:
>pip install pylint
確認(rèn)pylint安裝成功:
>pylint --version
No config file found, using default configuration
pylint 1.6.5,
astroid 1.4.9
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)]
-
生成默認(rèn)配置文件:
>pylint --persistent=n --generate-rcfile > pylint.conf
No config file found, using default configuration
查看當(dāng)前目錄下反浓,已經(jīng)生成了名為pylint.conf的文件钧惧,該文件中的配置項(xiàng)都是pylint的默認(rèn)配置,比較大400多行勾习。
-
check單個(gè)文件:
>pylint --rcfile=pylint.conf manage.py
- check結(jié)果總覽:
************* Module manage
C: 1, 0: Missing module docstring (missing-docstring)
W: 14,12: Unused import django (unused-import)
報(bào)告中上述格式為檢查結(jié)果總覽:C表示convention浓瞪,規(guī)范;W表示warning巧婶,告警乾颁;pylint結(jié)果總共有四個(gè)級(jí)別:error,warning艺栈,refactor英岭,convention,可以根據(jù)首字母確定相應(yīng)的級(jí)別湿右。1, 0表示告警所在文件中的行號(hào)和列號(hào)诅妹。
- 4種級(jí)別告警匯總:
Messages by category
+-----------+-------+---------+-----------+
|type |number |previous |difference |
+===========+=======+=========+===========+
|convention |1 |NC |NC |
+-----------+-------+---------+-----------+
|refactor |0 |NC |NC |
+-----------+-------+---------+-----------+
|warning |1 |NC |NC |
+-----------+-------+---------+-----------+
|error |0 |NC |NC |
+-----------+-------+---------+-----------+
- 消息類型統(tǒng)計(jì):
Messages
+------------------+------------+
|message id |occurrences |
+==================+============+
|mixed-indentation |8 |
+------------------+------------+
|unused-import |2 |
+------------------+------------+
|invalid-name |2 |
+------------------+------------+
|redefined-builtin |1 |
+------------------+------------+
-
check整個(gè)工程:
目前看只能一個(gè)module一個(gè)module的pylint,但是如果在工程根目錄下添加init.py文件毅人,即把工程當(dāng)做一個(gè)python包的話吭狡,可以對(duì)整個(gè)工程進(jìn)行pylint。
pylint api(api為包名稱)
重命名pylint.conf為.pylintrc丈莺,即不需要每次執(zhí)行都帶上--rcfile參數(shù)了:
pylintrc in the current working directory
.pylintrc in the current working directory
If the current working directory is in a Python module, Pylint searches up the hierarchy of Python modules until it finds a pylintrc file. This allows you to specify coding standards on a module-by-module basis. Of course, a directory is judged to be a Python module if it contains an __init__.py file.
The file named by environment variable PYLINTRC
if you have a home directory which isn’t /root:
.pylintrc in your home directory
.config/pylintrc in your home directory
/etc/pylintrc
pylint集成到PyCharm:
打開File->設(shè)置對(duì)話框:
單擊Tools中External Tools划煮,添加External Tool:
這樣修改完代碼后,Tools菜單下就會(huì)多出pylint工具了:
如果想要pylint當(dāng)前文件缔俄,只要運(yùn)行上圖的pylint工具即可弛秋。