需求背景:
Pylint 是一個 Python 代碼分析工具,它分析 Python 代碼中的錯誤,查找不符合代碼風格標準和有潛在問題的代碼。
Pylint 是一個 Python 工具,除了平常代碼分析工具的作用之外,它提供了更多的功能:如檢查一行代碼的長度,變量名是否符合命名標準,一個聲明過的接口是否被真正實現等等。
Pylint 的一個很大的好處是它的高可配置性,高可定制性,并且可以很容易寫小插件來添加功能。
項目中需要做代碼規范檢查,所以研究一下pylint的使用。
pylint使用:
-
安裝pylint:
>pip install pylint
確認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)]
-
生成默認配置文件:
>pylint --persistent=n --generate-rcfile > pylint.conf
No config file found, using default configuration
查看當前目錄下,已經生成了名為pylint.conf的文件,該文件中的配置項都是pylint的默認配置,比較大400多行。
-
check單個文件:
>pylint --rcfile=pylint.conf manage.py
- check結果總覽:
************* Module manage
C: 1, 0: Missing module docstring (missing-docstring)
W: 14,12: Unused import django (unused-import)
報告中上述格式為檢查結果總覽:C表示convention,規范;W表示warning,告警;pylint結果總共有四個級別:error,warning,refactor,convention,可以根據首字母確定相應的級別。1, 0表示告警所在文件中的行號和列號。
- 4種級別告警匯總:
Messages by category
+-----------+-------+---------+-----------+
|type |number |previous |difference |
+===========+=======+=========+===========+
|convention |1 |NC |NC |
+-----------+-------+---------+-----------+
|refactor |0 |NC |NC |
+-----------+-------+---------+-----------+
|warning |1 |NC |NC |
+-----------+-------+---------+-----------+
|error |0 |NC |NC |
+-----------+-------+---------+-----------+
- 消息類型統計:
Messages
+------------------+------------+
|message id |occurrences |
+==================+============+
|mixed-indentation |8 |
+------------------+------------+
|unused-import |2 |
+------------------+------------+
|invalid-name |2 |
+------------------+------------+
|redefined-builtin |1 |
+------------------+------------+
-
check整個工程:
目前看只能一個module一個module的pylint,但是如果在工程根目錄下添加init.py文件,即把工程當做一個python包的話,可以對整個工程進行pylint。
pylint api(api為包名稱)
重命名pylint.conf為.pylintrc,即不需要每次執行都帶上--rcfile參數了:
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->設置對話框:
settings.png
單擊Tools中External Tools,添加External Tool:
Create Tool.png
這樣修改完代碼后,Tools菜單下就會多出pylint工具了:
pylint.png
如果想要pylint當前文件,只要運行上圖的pylint工具即可。