[Dynamic Language] Pylint 分析Python代码格式规范

时间:2022-01-05 08:16:34

Pylint 是一个 Python 代码分析工具,它分析 Python 代码中的错误,查找不符合代码风格标准(Pylint 默认使用的代码风格是 PEP 8)和有潜在问题的代码。
    * Pylint 是一个 Python 工具,除了平常代码分析工具的作用之外,它提供了更多的功能:如检查一行代码的长度,变量名是否符合命名标准,一个声明过的接口是否被真正实现等。
    * Pylint 的一个很大的好处是它的高可配置性,高可定制性,并且可以很容易写小插件来添加功能。
    * 如果运行两次 Pylint,它会同时显示出当前和上次的运行结果,从而可以看出代码质量是否得到了改进。

演示代码:

1 # !/usr/bin/env python
2 # _*_ conding:utf-8 _*_
3
4 import datetime
5
6 class MyFile:
7 def __init__ (self, file_full_name):
8 self. __file_full_name = file_full_name
9
10 def append(self, value):
11 f = open(self. __file_full_name , ' a ' )
12 f.write(value)
13 f.close()
14
15 def content(self):
16 f = open(self. __file_full_name , ' r ' )
17 return f.read()
18
19
20 if __name__ == " __main__ " :
21 f = MyFile( ' test.txt ' )
22 f.append( " abeen.... " + str(datetime.datetime.now()) + " \n " )
23 print f.content()

代码分析结果:
abeen@localhost:~/learn_test/file$ pylint file_test.py
************* Module file_test
C:  1: Missing docstring
C:  6:MyFile: Missing docstring
W: 11:MyFile.append: Redefining name 'f' from outer scope (line 21)
C: 10:MyFile.append: Missing docstring
C: 11:MyFile.append: Invalid name "f" (should match [a-z_][a-z0-9_]{2,30}$)
W: 16:MyFile.content: Redefining name 'f' from outer scope (line 21)
C: 15:MyFile.content: Missing docstring
C: 16:MyFile.content: Invalid name "f" (should match [a-z_][a-z0-9_]{2,30}$)
C: 21: Invalid name "f" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)

Report
======
15 statements analysed.

Raw metrics
-----------

+----------+-------+------+---------+-----------+
|type      |number |%     |previous |difference |
+==========+=======+======+=========+===========+
|code      |16     |80.00 |16       |=          |
+----------+-------+------+---------+-----------+
|docstring |0      |0.00  |0        |=          |
+----------+-------+------+---------+-----------+
|comment   |2      |10.00 |2        |=          |
+----------+-------+------+---------+-----------+
|empty     |2      |10.00 |2        |=          |
+----------+-------+------+---------+-----------+

Duplication
-----------

+-------------------------+------+---------+-----------+
|                         |now   |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines      |0     |0        |=          |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000    |=          |
+-------------------------+------+---------+-----------+

Statistics by type
------------------

+---------+-------+-----------+-----------+------------+---------+
|type     |number |old number |difference |%documented |%badname |
+=========+=======+===========+===========+============+=========+
|module   |1      |1          |=          |0.00        |0.00     |
+---------+-------+-----------+-----------+------------+---------+
|class    |1      |1          |=          |0.00        |0.00     |
+---------+-------+-----------+-----------+------------+---------+
|method   |3      |3          |=          |33.33       |0.00     |
+---------+-------+-----------+-----------+------------+---------+
|function |0      |0          |=          |0.00        |0.00     |
+---------+-------+-----------+-----------+------------+---------+

Messages by category
--------------------

+-----------+-------+---------+-----------+
|type       |number |previous |difference |
+===========+=======+=========+===========+
|convention |7      |7        |=          |
+-----------+-------+---------+-----------+
|refactor   |0      |0        |=          |
+-----------+-------+---------+-----------+
|warning    |2      |2        |=          |
+-----------+-------+---------+-----------+
|error      |0      |0        |=          |
+-----------+-------+---------+-----------+

Messages
--------

+-----------+------------+
|message id |occurrences |
+===========+============+
|C0111      |4           |
+-----------+------------+
|C0103      |3           |
+-----------+------------+
|W0621      |2           |
+-----------+------------+

Global evaluation
-----------------
Your code has been rated at 4.00/10 (previous run: 4.00/10)

修改后代码:

 

1 # !/usr/bin/env python
2 # _*_ conding:utf-8 _*_
3
4 """
5 test class
6 author : abeen
7 email : abeen_8298@msn.com
8
"""
9
10 class MyFile:
11 """ class """
12 def __init__ (self, file_full_name):
13 self. __file_full_name = file_full_name
14
15 def append(self, value):
16 """ append """
17 current_file = open(self. __file_full_name , ' a ' )
18 current_file.write(value)
19 current_file.close()
20
21 def content(self):
22 """ content """
23 current_file = open(self. __file_full_name , ' r ' )
24 return current_file.read()

代码分析:
abeen@localhost:~/learn_test/file$ pylint file_test.py
No config file found, using default configuration

Report
======
10 statements analysed.

Raw metrics
-----------

+----------+-------+------+---------+-----------+
|type      |number |%     |previous |difference |
+==========+=======+======+=========+===========+
|code      |11     |45.83 |11       |=          |
+----------+-------+------+---------+-----------+
|docstring |8      |33.33 |8        |=          |
+----------+-------+------+---------+-----------+
|comment   |2      |8.33  |2        |=          |
+----------+-------+------+---------+-----------+
|empty     |3      |12.50 |3        |=          |
+----------+-------+------+---------+-----------+

Duplication
-----------

+-------------------------+------+---------+-----------+
|                         |now   |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines      |0     |0        |=          |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000    |=          |
+-------------------------+------+---------+-----------+

Statistics by type
------------------

+---------+-------+-----------+-----------+------------+---------+
|type     |number |old number |difference |%documented |%badname |
+=========+=======+===========+===========+============+=========+
|module   |1      |1          |=          |100.00      |0.00     |
+---------+-------+-----------+-----------+------------+---------+
|class    |1      |1          |=          |100.00      |0.00     |
+---------+-------+-----------+-----------+------------+---------+
|method   |3      |3          |=          |100.00      |0.00     |
+---------+-------+-----------+-----------+------------+---------+
|function |0      |0          |=          |0.00        |0.00     |
+---------+-------+-----------+-----------+------------+---------+

Messages by category
--------------------

+-----------+-------+---------+-----------+
|type       |number |previous |difference |
+===========+=======+=========+===========+
|convention |0      |0        |=          |
+-----------+-------+---------+-----------+
|refactor   |0      |0        |=          |
+-----------+-------+---------+-----------+
|warning    |0      |0        |=          |
+-----------+-------+---------+-----------+
|error      |0      |0        |=          |
+-----------+-------+---------+-----------+

Global evaluation
-----------------
Your code has been rated at 10.00/10 (previous run: 10.00/10)


Pylint 的常用命令行参数
    * -h,--help
      显示所有帮助信息。
    * --generate-rcfile
      可以使用 pylint --generate-rcfile 来生成一个配置文件示例。可以使用重定向把这个配置文件保存下来用做以后使用。也可以在前面加上其它选项,使这些选项的值被包含在这个产生的配置文件里。如:pylint --persistent=n --generate-rcfile > pylint.conf,查看 pylint.conf,可以看到 persistent=no,而不再是其默认值 yes。
    * --rcfile=<file>
      指定一个配置文件。把使用的配置放在配置文件中,这样不仅规范了自己代码,也可以方便地和别人共享这些规范。
    * -i <y_or_n>, --include-ids=<y_or_n>
      在输出中包含 message 的 id, 然后通过 pylint --help-msg=<msg-id>来查看这个错误的详细信息,这样可以具体地定位错误。
    * -r <y_or_n>, --reports=<y_or_n>
      默认是 y, 表示 Pylint 的输出中除了包含源代码分析部分,也包含报告部分。
    * --files-output=<y_or_n>
      将每个 module /package 的 message 输出到一个以 pylint_module/package. [txt|html] 命名的文件中,如果有 report 的话,输出到名为 pylint_global.[txt|html] 的文件中。默认是输出到屏幕上不输出到文件里。
    * -f <format>, --output-format=<format>
      设置输出格式。可以选择的格式有 text, parseable, colorized, msvs (visual studio) 和 html, 默认的输出格式是 text。
    * --disable-msg= <msg ids>
      禁止指定 id 的 message. 比如说输出中包含了 W0402 这个 warning 的 message, 如果不希望它在输出中出现,可以使用 --disable-msg= W0402
     
     
源代码分析:
对于每一个 Python 模块,Pylint 的结果中首先显示一些"*"字符 , 后面紧跟模块的名字,然后是一系列的 message, message 的格式如下:
 MESSAGE_TYPE: LINE_NUM:[OBJECT:] MESSAGE

MESSAGE_TYPE 有如下几种:
(C) 惯例。违反了编码风格标准
(R) 重构。写得非常糟糕的代码。
(W) 警告。某些 Python 特定的问题。
(E) 错误。很可能是代码中的错误。
(F) 致命错误。阻止 Pylint 进一步运行的错误。


报告部分:
在源代码分析结束后面,会有一系列的报告,每个报告关注于项目的某些方面,如每种类别的 message 的数目,模块的依赖关系等等。具体来说,报告中会包含如下的方面:
    o 检查的 module 的个数。
    o 对于每个 module, 错误和警告在其中所占的百分比。比如有两个 module A 和 B, 如果一共检查出来 4 个错误,1 个错误是在 A 中,3 个错误是在 B 中,那么 A 的错误的百分比是 25%, B 的错误的百分比是 75%。
    o 错误,警告的总数量。

 

 


 下面是python 常量、变量、类名等 各种命名规则.

[Dynamic Language] Pylint 分析Python代码格式规范