pylint的配置与使用
来源:互联网 发布:功德人生软件下载 编辑:程序博客网 时间:2024/05/30 23:21
简介
本文主要介绍pylint的配置与使用,如何安装请参考pylint安装,详细信息可参考pylint官方网站的帮助文档Pylint User Manual。
获取帮助信息
pylint安装成功后,可以通过运行"pylint --help"来快速查看pylint的帮助信息;相关信息基本能够支撑起快速使用起来pylint的基本功能。
bob@Ubuntu:~$ pylint --helpNo config file found, using default configurationUsage: 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 messagesreports=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 commarequired-attributes=# List of builtins function names that should not be used, separated by a commabad-functions=map,filter,apply,input# Regular expression which should only match correct module namesmodule-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$# Regular expression which should only match correct module level namesconst-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$# Regular expression which should only match correct class namesclass-rgx=[A-Z_][a-zA-Z0-9]+$# Regular expression which should only match correct function namesfunction-rgx=[a-z_][a-z0-9_]{2,30}$# Regular expression which should only match correct method namesmethod-rgx=[a-z_][a-z0-9_]{2,30}$# Regular expression which should only match correct instance attribute namesattr-rgx=[a-z_][a-z0-9_]{2,30}$# Regular expression which should only match correct argument namesargument-rgx=[a-z_][a-z0-9_]{2,30}$# Regular expression which should only match correct variable namesvariable-rgx=[a-z_][a-z0-9_]{2,30}$# Regular expression which should only match correct attribute names in class# bodiesclass-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$# Regular expression which should only match correct list comprehension /# generator expression variable namesinlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$# Good variable names which should always be accepted, separated by a commagood-names=i,j,k,ex,Run,_# Bad variable names which should always be refused, separated by a commabad-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 modulemax-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 / methodmax-args=5# Argument names that match this expression will be ignored. Default to name# with leading underscoreignored-argument-names=_.*# Maximum number of locals for function / method bodymax-locals=15# Maximum number of return / yield for function / method bodymax-returns=6# Maximum number of branch for function / method bodymax-branches=12# Maximum number of statements in function / method bodymax-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 commadeprecated-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)报告中安装上述的格式生成检查结果,W代表生成的检查级别,级别分为4种:error, warning, refactor, convention;可以根据首字母来对应相应的级别。"10, 0" 代表告警所在源码文件中的行号和列号,可以通过Eclipse中CTRL+L快捷键快速查找所在到问题所在的行。“Unused import help"表述问题的详细信息。”(unused-import)为问题的消息ID信息。
下面的信息是按照消息的类别进行分类,对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__ = Noneclass 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安装
2. http://docs.pylint.org/
- pylint的配置与使用
- pylint的配置和使用
- 配置 eclipse +pydev + pylint
- Python语法检查引用PyLint配置的具体方法
- pylint 使用命令
- pylint的介绍
- pylint的安装
- pylint
- Python代码规范与pylint
- 如何安装及使用pyLint
- 使用pylint 规范python代码
- Eclipse + Pydev 下配置Django,并使用pylint进行静态检测
- windows下配置eclipse + Python + PyDev + tornado,并使用pylint进行静态检测
- windows下配置eclipse + Python + PyDev + tornado,并使用pylint进行静态检测
- 解决sublime使用pylint插件时对django的支持问题
- pychecker以及pylint的安装以及使用方法
- 使用 pylint 检测python代码质量(sonar-scanner调用pylint,然后数据交给sonar服务器)
- 用Pylint规范化Python代码,附PyCharm配置
- Xcode 如何把數字格式化 : NSNumberFormatter
- 移动端笔记 关闭iOS键盘首字母自动大写
- 用C语言Linux下打印带颜色的字符串
- 自己写一个app,遇到listview滑动卡顿的问题。
- HDU 3278 Catch That Cow(简单bfs)
- pylint的配置与使用
- Oracle函数介绍:decode
- Phaser 编程技巧
- Tinycore学习笔记_快速安装系统
- java编程思想第四版习题_8.11
- Leetcode_Add Binary
- codeforces 30C Shooting Gallery (概率dp)
- WebClient访问FTP服务器时505错误
- 基于百度地图API的微信周边搜索