利用pylint 檢測 python源碼。
Pylint 提供了簡單的方式來分析 Python 代碼,其高可配置性很容易使一個部門的人員使用統一的代碼風格。
Pylint 是什么
Pylint 是一個 Python 代碼分析工具,它分析 Python 代碼中的錯誤,查找不符合代碼風格標准(Pylint 默認使用的代碼風格是 PEP 8,具體信息,請參閱參考資料)和有潛在問題的代碼。目前 Pylint 的最新版本是 pylint-0.18.1。
- Pylint 是一個 Python 工具,除了平常代碼分析工具的作用之外,它提供了更多的功能:如檢查一行代碼的長度,變量名是否符合命名標准,一個聲明過的接口是否被真正實現等等。
- Pylint 的一個很大的好處是它的高可配置性,高可定制性,並且可以很容易寫小插件來添加功能。
- 如果運行兩次 Pylint,它會同時顯示出當前和上次的運行結果,從而可以看出代碼質量是否得到了改進。
- 目前在 eclipse 的 pydev 插件中也集成了 Pylint。
Pylint 的最新包下載:http://www.logilab.org/project/pylint
Pylint 的安裝
Pylint 可以用於所有高於或者等於 2.2 的 Python 版本兼容。需要 logilab-astng(version >= 0.14)和 logilab-common(version >= 0.13)的包(具體信息,請參閱 參考資料),如果是 Python 版本低於 2.3,那么它還需要 optik 包(本文接下來的示例暫不考慮這種情況)。
Pylint 所用到的所有的包的下載地址
logilab-astng 的最新包下載:http://www.logilab.org/856/
logilab-common 的最新包下載:http://www.logilab.org/848/
optik 的包下載:http://optik.sourceforge.net/
Pylint 的最新包下載:http://www.logilab.org/project/pylint
Pylint 在 Linux 上的安裝
1. 在 Linux 上,首先安裝 Python 的包(高於版本 2.2),並在環境變量 $PATH 中添加 Python 可執行文件的路徑。
2. 下載 Pylint、logilab-astng (version >= 0.14) 和 logilab-common (version >= 0.13) 的包 , 使用 tar zxvf *.tar.gz
解壓縮這些包。
3. 依次進入 logilab-astng、logilab-common 和 Pylint 解開的文件夾中,運行命令 Python setup.py install
來安裝。
4. 安裝完成后,就可以通過 pylint [options] module_or_package
來調用 Pylint 了。
Pylint 在 Windows 上的安裝
1. 安裝 Python 的包(高於版本 2.2),右鍵單擊桌面上的我的電腦圖標,選擇屬性,高級,環境變量,在 $PATH 中添加 Python 的安裝路徑,如 C:\Python26\。
2. 使用解壓縮工具解壓縮所有的包。
3. 打開命令行窗口,使用 cd
依次進入 logilab-astng、logilab-common 和 Pylint 解開的文件夾中,運行命令 python setup.py install
來安裝。
4. 安裝完成后,在 Python 的安裝路徑下出現一個 Scripts 文件夾,里面包含一些 bat 腳本,如 pylint.bat 等。
5. 為了使調用 pylint.bat 的時候不需要輸入完整路徑,在 Python 的安裝目錄下創建 pylint.bat 的重定向文件,這是一個純文本文件 pylint.bat,里面包含 pylint.bat 的實際路徑,如:C:\Python26\Scripts\pylint.bat。
6. 安裝完成后,可以通過 pylint [options] module_or_package
來調用 Pylint 了。
命令
使用命令 pylint --help 或 man pylint 查看更詳細的用法。
Usage: pylint [options] module_or_package Check that a module satisfies a coding standard (and more !). pylint --help Display this help message and exit. pylint --help-msg <msg-id>[,<msg-id>] Display help messages about given message identifiers and exit. Options: --version show program's version number and exit -h, --help show this help message and exit
顯示所有幫助信息。 --long-help more verbose help. Master: --rcfile=<file> Specify a configuration file.
指定一個配置文件。把使用的配置放在配置文件中,這樣不僅規范了自己代碼,也可以方便地和別人共享這些規范。 --init-hook=<code> Python code to execute, usually for sys.path manipulation such as pygtk.require(). -E, --errors-only In error mode, checkers without error messages are disabled and for others, only the ERROR messages are displayed, and no reports are done by default --py3k In Python 3 porting mode, all checkers will be disabled and only messages emitted by the porting checker will be displayed --ignore=<file>[,<file>...] Add files or directories to the blacklist. They should be base names, not paths. [current: CVS] --ignore-patterns=<pattern>[,<pattern>...] Add files or directories matching the regex patterns to the blacklist. The regex matches against base names, not paths. [current: none] --persistent=<y_or_n> Pickle collected data for later comparisons. [current: yes] --load-plugins=<modules> List of plugins (as comma separated values of python modules names) to load, usually to register additional checkers. [current: none] -j <n-processes>, --jobs=<n-processes> Use multiple processes to speed up Pylint. [current: 1] --extension-pkg-whitelist=<pkg[,pkg]> A comma-separated list of package or module names from where C extensions may be loaded. Extensions are loading into the active Python interpreter and may run arbitrary code [current: none] --optimize-ast=<yn> Allow optimization of some AST trees. This will activate a peephole AST optimizer, which will apply various small optimizations. For instance, it can be used to obtain the result of joining multiple strings with the addition operator. Joining a lot of strings can lead to a maximum recursion error in Pylint and this flag can prevent that. It has one side effect, the resulting AST will be different than the one from reality. This option is deprecated and it will be removed in Pylint 2.0. [current: no] Commands: --help-msg=<msg-id> Display a help message for the given message id and exit. The value may be a comma separated list of message ids. --list-msgs Generate pylint's messages. --list-conf-levels Generate pylint's messages. --full-documentation Generate pylint's full documentation. --generate-rcfile Generate a sample configuration file according to the current configuration. You can put other options before this one to get them in the generated configuration.
可以使用 pylint --generate-rcfile 來生成一個配置文件示例。可以使用重定向把這個配置文件保存下來用做以后使用。也可以在前面加上其它選項,使這些選項的值被包含在這個產生的配置文件里。如:pylint --persistent=n --generate-rcfile > pylint.conf
,查看 pylint.conf,可以看到 persistent=no,而不再是其默認值 yes。 Messages control: --confidence=<levels> Only show warnings with the listed confidence levels. Leave empty to show all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED [current: none] -e <msg ids>, --enable=<msg ids> Enable the message, report, category or checker with the given id(s). You can either give multiple identifier separated by comma (,) or put this option multiple time (only on the command line, not in the configuration file where it should appear only once). See also the "--disable" option for examples. -d <msg ids>, --disable=<msg ids> Disable the message, report, category or checker with the given id(s). You can either give multiple identifiers separated by comma (,) or put this option multiple times (only on the command line, not in the configuration file where it should appear only once).You can also use "--disable=all" to disable everything first and then reenable specific checks. For example, if you want to run only the similarities checker, you can use "--disable=all --enable=similarities". If you want to run only the classes checker, but have no Warning level messages displayed, use"--disable=all --enable=classes --disable=W"
禁止指定 id 的 message. 比如說輸出中包含了 W0402 這個 warning 的 message, 如果不希望它在輸出中出現,可以使用--disable-msg= W0402
Reports: -f <format>, --output-format=<format> Set the output format. Available formats are text, parseable, colorized, msvs (visual studio) and html. You can also give a reporter class, eg mypackage.mymodule.MyReporterClass. [current: text]
設置輸出格式。可以選擇的格式有 text, parseable, colorized, msvs (visual studio) 和 html, 默認的輸出格式是 text。 --files-output=<y_or_n> Put messages in a separate file for each module / package specified on the command line instead of printing them on stdout. Reports (if any) will be written in a file name "pylint_global.[txt|html]". This option is deprecated and it will be removed in Pylint 2.0. [current: no]
將每個 module /package 的 message 輸出到一個以 pylint_module/package. [txt|html] 命名的文件中,如果有 report 的話,輸出到名為 pylint_global.[txt|html] 的文件中。默認是輸出到屏幕上不輸出到文件里。 -r <y_or_n>, --reports=<y_or_n> Tells whether to display a full report or only the messages [current: yes]
默認是 y, 表示 Pylint 的輸出中除了包含源代碼分析部分,也包含報告部分。 --evaluation=<python_expression> Python expression which should return a note less than 10 (10 is the highest note). You have access to the variables errors warning, statement which respectively contain the number of errors / warnings messages and the total number of statements analyzed. This is used by the global evaluation report (RP0004). [current: 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)] --msg-template=<template> Template used to display messages. This is a python new-style format string used to format the message information. See doc for all details
配置
使用如下命令
#pylint --generate-rcfile > pylint.conf
生成一個配置文件模板,然后可以根據這個模板作個性化修改以適應具體項目的需求。
配置文件的模板參見pylint.conf 。 可以在模板文件上定制相關的統一的配置文件。配置文件中包含了master, message control, reports, typecheck, similarities, basic, variables, format, design, classes, imports, exception相關的lint配置信息,用戶可以進行私人訂制。
修改部分說明:
disable=I0011
禁止 locally-disabled 類型的消息輸出。
output-format=colorized
配置輸出着色。
reports=no
不顯示完整的報告,只顯示消息。
const-rgx=[a-z_][a-z0-9_]{2,30}$
配置模塊級別的常量和變量的命名規則(以小寫字母或下划線開頭后續跟着小寫字母或數字或下划線,2到30個字符)。
good-names=i,j,k,n,ex,Run,_
添加一個總是接受的命名 “n”。
最新版的pylint已經廢棄 --include-ids=<y_or_n>, -i <y_or_n> 選項,可在配置文件里修改輸出消息的格式:
msg-template='{msg_id}:{line:3d}, {column}: {msg} ({symbol})'
Pylint 的輸出
Pylint的默認輸出格式是原始文
本(raw text)格式 ,可以通過 -f <format>,--output-format=<format> 來指定別的輸出格式如
html等等。在
Pylint的輸出中有如下兩個部分:源代碼分析部分
和報告部分。
源代碼分析部分:
對於每一個 Python 模塊,Pylint 的結果中首先顯示一些"*"字符 , 后面緊跟模塊的名字,然后是一系列的 message, message 的格式如下:
MESSAGE_TYPE: LINE_NUM:[OBJECT:] MESSAGE
MESSAGE_TYPE 有如下幾種:
(C) convention 慣例。違反了編碼風格標准
(R) refactor 重構。寫得非常糟糕的代碼。
(W) warning 警告。某些 Python 特定的問題。
(E) error 錯誤。很可能是代碼中的錯誤。
(F) fatal 致命錯誤。阻止 Pylint 進一步運行的錯誤。
************* Module utils C: 88:Message: Missing docstring R: 88:Message: Too few public methods (0/2) C:183:MessagesHandlerMixIn._cat_ids: Missing docstring R:183:MessagesHandlerMixIn._cat_ids: Method could be a function R:282:MessagesHandlerMixIn.list_messages: Too many branches (14/12)
報告部分:
在源代碼分析結束后面,會有一系列的報告,每個報告關注於項目的某些方面,如每種類別的 message 的數目,模塊的依賴關系等等。具體來說,報告中會包含如下的方面:
- 檢查的 module 的個數。
- 對於每個 module, 錯誤和警告在其中所占的百分比。比如有兩個 module A 和 B, 如果一共檢查出來 4 個錯誤,1 個錯誤是在 A 中,3 個錯誤是在 B 中,那么 A 的錯誤的百分比是 25%, B 的錯誤的百分比是 75%。
- 錯誤,警告的總數量。
使用
使用 Pylint 對一個模塊 module.py 進行代碼檢查:
pylint [options] module_or_package
- 1. 進入這個模塊所在的文件夾,運行
pylint [options] module.py
這種調用方式是一直可以工作的,因為當前的工作目錄會被自動加入 Python 的路徑中。 - 2. 不進入模塊所在的文件夾,運行
pylint [options] directory/module.py
這種調用方式當如下條件滿足的時候是可以工作的:directory 是個 Python 包 ( 比如包含一個 __init__.py 文件 ),或者 directory 被加入了 Python 的路徑中。
使用 Pylint 對一個包 pakage 進行代碼檢查:
-
- 1. 進入這個包所在文件夾,運行
pylint [options] pakage。
這種調用方式是一直可以工作的,因為當前的工作目錄會被自動加入 Python 的路徑中。 - 2. 不進入包所在的文件夾,運行
pylint [options] directory/ pakage。
這種情況下當如下條件滿足的時候是可以工作的:directory 被加入了 Python 的路徑中。比如在 Linux 上,export PYTHONPATH=$PYTHONPATH: directory。
- 1. 進入這個包所在文件夾,運行
此外,對於安裝了 tkinter 包的機器,可以使用命令 pylint-gui
打開一個簡單的 GUI 界面,在這里輸入模塊或者包的名字 ( 規則同命令行 ), 點擊 Run,Pylint 的輸出會在 GUI 中顯示。
在代碼中關閉某個告警消息:
模塊級別:
#! usr/bin/python #pylint: disable=invalid-name ''' Docstring... '''
行級別:
def file_travesal(dirtectory='.', file_list=[]): # pylint: disable=W0102 ''' Get file list from the directory including files in its subdirectories. ''' file_list += [join(dirtectory, f) for f in listdir(dirtectory) if isfile(join(dirtectory, f))] for item in listdir(dirtectory): if isdir(join(dirtectory, item)): file_travesal(join(dirtectory, item), file_list)
添加命令別名(配置文件在用戶目錄“~/”下):
echo "alias pylt='pylint --rcfile=~/pylint.conf'" >> ~/.bashrc
怎么更改pylint的默認配置文件
pylint安裝成功后,可以通過運行"pylint --help"來快速查看pylint的幫助信息;相關信息基本能夠支撐起快速使用起來pylint的基本功能。
可以通過"pylint --generate-rcfile"生成配置文件模板,可以在模板文件上定制相關的統一的配置文件。配置文件中包含了master, message control, reports, typecheck, similarities, basic, variables, format, design, classes, imports, exception相關的lint配置信息,用戶可以進行私人訂制。
jenkins中的violations插件
https://wiki.jenkins-ci.org/display/JENKINS/Violations
參考
http://www.ibm.com/developerworks/cn/linux/l-cn-pylint/
https://wiki.jenkins-ci.org/display/JENKINS/Violations