Eins
简介
本文主要介绍pylint的配置与使用,如何安装请参考pylint安装,详细信息可参考pylint官方网站的帮助文档Pylint User Manual。
获取帮助信息
pylint安装成功后,可以通过运行"pylint --help"来快速查看pylint的帮助信息;相关信息基本能够支撑起快速使用起来pylint的基本功能。
- bob@Ubuntu:~$ pylint --help
- No config file found, using default configuration
- 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.
- -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
- --ignore=<file>[,<file>...]
- Add files or directories to the blacklist. They should
- be base names, not paths. [current: CVS]
- 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.
- --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.
- Messages control:
- -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. 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"
- 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]
- -r <y_or_n>, --reports=<y_or_n>
- Tells whether to display a full report or only the
- messages [current: yes]
- --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"生成配置文件模板,可以在模板文件上定制相关的统一的配置文件。配置文件中包含了master, message control, reports, typecheck, similarities, basic, variables, format, design, classes, imports, exception相关的lint配置信息,用户可以进行私人订制。
- bob@Ubuntu:~$ cat pylint.conf
- [MASTER]
- # Specify a configuration file.
- #rcfile=
- # Python code to execute, usually for sys.path manipulation such as
- # pygtk.require().
- #init-hook=
- # Profiled execution.
- profile=no
- # Add files or directories to the blacklist. They should be base names, not
- # paths.
- ignore=CVS
- # Pickle collected data for later comparisons.
- persistent=yes
- # List of plugins (as comma separated values of python modules names) to load,
- # usually to register additional checkers.
- load-plugins=
- [MESSAGES CONTROL]
- # 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. See also the "--disable" option for examples.
- #enable=
- # 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"
- #disable=
- disable=logging-not-lazy, line-too-long, trailing-whitespace, bare-except, broad-except
- [REPORTS]
- # 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.
- output-format=text
- # 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]".
- files-output=no
- # Tells whether to display a full report or only the messages
- reports=yes
- # 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).
- evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
- # Add a comment according to your evaluation note. This is used by the global
- # evaluation report (RP0004).
- comment=no
- # Template used to display messages. This is a python new-style format string
- # used to format the massage information. See doc for all details
- #msg-template=
- [TYPECHECK]
- # Tells whether missing members accessed in mixin class should be ignored. A
- # mixin class is detected if its name ends with "mixin" (case insensitive).
- ignore-mixin-members=yes
- # List of classes names for which member attributes should not be checked
- # (useful for classes with attributes dynamically set).
- ignored-classes=SQLObject
- # When zope mode is activated, add a predefined set of Zope acquired attributes
- # to generated-members.
- zope=no
- # List of members which are set dynamically and missed by pylint inference
- # system, and so shouldn't trigger E0201 when accessed. Python regular
- # expressions are accepted.
- generated-members=REQUEST,acl_users,aq_parent
- [SIMILARITIES]
- # Minimum lines number of a similarity.
- min-similarity-lines=4
- # Ignore comments when computing similarities.
- ignore-comments=yes
- # Ignore docstrings when computing similarities.
- ignore-docstrings=yes
- # Ignore imports when computing similarities.
- ignore-imports=no
- [BASIC]
- # Required attributes for module, separated by a comma
- required-attributes=
- # List of builtins function names that should not be used, separated by a comma
- bad-functions=map,filter,apply,input
- # Regular expression which should only match correct module names
- module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
- # Regular expression which should only match correct module level names
- const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
- # Regular expression which should only match correct class names
- class-rgx=[A-Z_][a-zA-Z0-9]+$
- # Regular expression which should only match correct function names
- function-rgx=[a-z_][a-z0-9_]{2,30}$
- # Regular expression which should only match correct method names
- method-rgx=[a-z_][a-z0-9_]{2,30}$
- # Regular expression which should only match correct instance attribute names
- attr-rgx=[a-z_][a-z0-9_]{2,30}$
- # Regular expression which should only match correct argument names
- argument-rgx=[a-z_][a-z0-9_]{2,30}$
- # Regular expression which should only match correct variable names
- variable-rgx=[a-z_][a-z0-9_]{2,30}$
- # Regular expression which should only match correct attribute names in class
- # bodies
- class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
- # Regular expression which should only match correct list comprehension /
- # generator expression variable names
- inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
- # Good variable names which should always be accepted, separated by a comma
- good-names=i,j,k,ex,Run,_
- # Bad variable names which should always be refused, separated by a comma
- bad-names=foo,bar,baz,toto,tutu,tata
- # Regular expression which should only match function or class names that do
- # not require a docstring.
- no-docstring-rgx=__.*__
- # Minimum line length for functions/classes that require docstrings, shorter
- # ones are exempt.
- docstring-min-length=-1
- [VARIABLES]
- # Tells whether we should check for unused import in __init__ files.
- init-import=no
- # A regular expression matching the beginning of the name of dummy variables
- # (i.e. not used).
- dummy-variables-rgx=_$|dummy
- # List of additional names supposed to be defined in builtins. Remember that
- # you should avoid to define new builtins when possible.
- additional-builtins=
- [FORMAT]
- # Maximum number of characters on a single line.
- max-line-length=120
- # Regexp for a line that is allowed to be longer than the limit.
- ignore-long-lines=^\s*(# )?<?https?://\S+>?$
- # Maximum number of lines in a module
- max-module-lines=1000
- # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
- # tab).
- indent-string=' '
- [MISCELLANEOUS]
- # List of note tags to take in consideration, separated by a comma.
- notes=FIXME,XXX,TODO
- [DESIGN]
- # Maximum number of arguments for function / method
- max-args=5
- # Argument names that match this expression will be ignored. Default to name
- # with leading underscore
- ignored-argument-names=_.*
- # Maximum number of locals for function / method body
- max-locals=15
- # Maximum number of return / yield for function / method body
- max-returns=6
- # Maximum number of branch for function / method body
- max-branches=12
- # Maximum number of statements in function / method body
- max-statements=50
- # Maximum number of parents for a class (see R0901).
- max-parents=7
- # Maximum number of attributes for a class (see R0902).
- max-attributes=7
- # Minimum number of public methods for a class (see R0903).
- min-public-methods=2
- # Maximum number of public methods for a class (see R0904).
- max-public-methods=20
- [CLASSES]
- # List of interface methods to ignore, separated by a comma. This is used for
- # instance to not check methods defines in Zope's Interface base class.
- ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by
- # List of method names used to declare (i.e. assign) instance attributes.
- defining-attr-methods=__init__,__new__,setUp
- # List of valid names for the first argument in a class method.
- valid-classmethod-first-arg=cls
- # List of valid names for the first argument in a metaclass class method.
- valid-metaclass-classmethod-first-arg=mcs
- [IMPORTS]
- # Deprecated modules which should not be used, separated by a comma
- deprecated-modules=regsub,TERMIOS,Bastion,rexec
- # Create a graph of every (i.e. internal and external) dependencies in the
- # given file (report RP0402 must not be disabled)
- import-graph=
- # Create a graph of external dependencies in the given file (report RP0402 must
- # not be disabled)
- ext-import-graph=
- # Create a graph of internal dependencies in the given file (report RP0402 must
- # not be disabled)
- int-import-graph=
- [EXCEPTIONS]
- # Exceptions that will emit a warning when being caught. Defaults to
- # "Exception"
检查源码文件
配置好rcfile配置文件后,就可以使用pylint开始对源码文件进行配置检查了,可以通过类似命令"pylint --rcfile=/home/bob/pylint.conf /opt/app/login/login.py"来完成,命令参数包含配置文件的路径和源码文件路径。
pylint会生成检查报告,接下来我们来解析报告的内容:
- W: 10, 0: Unused import help (unused-import)
下面的信息是按照消息的类别进行分类,对4种级别的告警信息进行汇总:
- Messages by category
- --------------------
- +-----------+-------+---------+-----------+
- |type |number |previous |difference |
- +===========+=======+=========+===========+
- |convention |2 |2 |= |
- +-----------+-------+---------+-----------+
- |refactor |0 |0 |= |
- +-----------+-------+---------+-----------+
- |warning |11 |11 |= |
- +-----------+-------+---------+-----------+
- |error |0 |0 |= |
- +-----------+-------+---------+-----------+
- Messages
- --------
- +------------------+------------+
- |message id |occurrences |
- +==================+============+
- |mixed-indentation |8 |
- +------------------+------------+
- |unused-import |2 |
- +------------------+------------+
- |invalid-name |2 |
- +------------------+------------+
- |redefined-builtin |1 |
- +------------------+------------+
获取告警帮助信息
如需对某告警类型获取帮助信息,可以使用"pylint --help-msg <msg-id>"命令来获取:
- bob@Ubuntu:~$ pylint --help-msg unused-import
- :unused-import (W0611): *Unused import %s*
- Used when an imported module or variable is not used. This message belongs to
- the variables checker.
局部关闭某告警类型
在某些情况,可能需要关闭某文件中的某些告警类型,而非配置文件那种全局配置的情况,可以通过下列的方式来达到目的,通过注释的方式,来禁掉某些检查,如对meth2函数不检查未使用的参数情况。
- """pylint option block-disable"""
- __revision__ = None
- class Foo(object):
- """block-disable test"""
- def __init__(self):
- pass
- def meth1(self, arg):
- """this issues a message"""
- print self
- def meth2(self, arg):
- """and this one not"""
- # pylint: disable=unused-argument
- print self\
- + "foo"
小结
通过本文的介绍,基本可以快速使用pylint来对Python代码进行静态代码的检查;如果想获取更多使用或配置信息,可以查看官网的帮助文档:http://docs.pylint.org/
参考资料
1. pylint安装
Zwei
pylint在项目中的使用
需求背景:
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->设置对话框:
单击 Tools中 External Tools,添加External Tool:
这样修改完代码后,Tools菜单下就会多出pylint工具了:
如果想要pylint当前文件,只要运行上图的pylint工具即可。
参考资料:
Drei
PyCharm 中使用 Pylint 控制代码质量
1) Pylint安装
- Windows下:
直接在 cmd 下使用 pip install pylint 即可(如果 pip 不可用,首先安装最新版 Python,会默认安装 pip,或者找到 pip 的安装脚本先装 pip)。装好后,pylint.exe 的大体位置在 C:/Python27/Scripts/ 底下,将此路径添加到环境变量 PATH。
- Linux 下:
直接在 Terminal 中使用 $ sudo pip install pylint 安装即可。装好后,pylint 会在 /usr/bin/pylint
2) 配置 PyCharm
File > Settings... > Tools > External Tools,点击 + 号添加,如下图配置,
其中,
Program设置为: 指向 pylint 的实际目录,此处以 Linux 目录为例。
Parameters 设置为 (用户可根据自己的情况,选择 pylint 输出信息显示格式和要 disable 的项目):--output-format=parseable --disable=R --disable=C0102,C0103,C0111,C0301,C0302,C0303,C0304,C0305,W0120,W0123,W0401,W0603,W0612,W0614,W0621,W0622,W0703,E1003,E1101 $FilePath$
注:为了防止 Pylint 打印找不到 配置文件的 warning,可以在当前工程目录下新建一个空的文件,取名为 .pylintrc,再在上述参数中加入选项 --rcfile=path/to/.pylintrc 即可。
Working Direcroty 设置为:$FileDir$
3) 使用 Pylint 评估代码质量
当写完一个脚本后,直接右键单击,选择 External Tools > pylint,运行后可得到当前代码质量,和改进建议。