用Pylint规范化Python代码,附PyCharm配置

时间:2023-03-09 14:50:55
用Pylint规范化Python代码,附PyCharm配置

Pylint一个可以检查Python代码错误,执行代码规范的工具。它还可以对代码风格提出建议。

官网:https://pylint.readthedocs.io

pip install pylint

默认情况,Pylint就已经随着Python安装好。在Python的scripts目录下。

找一段小程序试验一下Pylint,程序很简单。

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. '''
  4. Created on 2017年2月4日
  5. @author: Arthur Guo
  6. '''
  7. N = 10
  8. YHTriangle = []
  9. for i in range(N):  # 行
  10. YHTriangle.append([])
  11. if i == 0:
  12. YHTriangle[i].append(1) #第一行只有 1
  13. else:
  14. YHTriangle[i].append(1) #最左元素永远为 1
  15. YHTriangle[i].append(1) #最右元素永远为 1
  16. for j in range(1,i):    #中间元素
  17. if i <> 0 and i <> 1:
  18. YHTriangle[i].insert(j,YHTriangle[i-1][j-1] + YHTriangle[i-1][j])
  19. for i in range(N):
  20. print YHTriangle[i]

命令行运行pylint yanghui.py,结果看起来很冗长

  1. c:\>c:\Python27\Scripts\pylint.exe d:\workspace\PyComm\src\Interviews\yanghui.py
  2. No config file found, using default configuration
  3. ************* Module Interviews.yanghui
  4. C: 19, 0: Exactly one space required after comma
  5. for j in range(1,i):    #中间元素
  6. ^ (bad-whitespace)
  7. C: 21, 0: Exactly one space required after comma
  8. YHTriangle[i].insert(j,YHTriangle[i-1][j-1] + YHTriangle[i-1][j]
  9. )
  10. ^ (bad-whitespace)
  11. C: 23, 0: Final newline missing (missing-final-newline)
  12. C: 11, 0: Invalid constant name "YHTriangle" (invalid-name)
  13. Report
  14. ======
  15. 13 statements analysed.
  16. Statistics by type
  17. ------------------
  18. +---------+-------+-----------+-----------+------------+---------+
  19. |type     |number |old number |difference |%documented |%badname |
  20. +=========+=======+===========+===========+============+=========+
  21. |module   |1      |1          |=          |100.00      |0.00     |
  22. +---------+-------+-----------+-----------+------------+---------+
  23. |class    |0      |0          |=          |0           |0        |
  24. +---------+-------+-----------+-----------+------------+---------+
  25. |method   |0      |0          |=          |0           |0        |
  26. +---------+-------+-----------+-----------+------------+---------+
  27. |function |0      |0          |=          |0           |0        |
  28. +---------+-------+-----------+-----------+------------+---------+
  29. Raw metrics
  30. -----------
  31. +----------+-------+------+---------+-----------+
  32. |type      |number |%     |previous |difference |
  33. +==========+=======+======+=========+===========+
  34. |code      |15     |62.50 |15       |=          |
  35. +----------+-------+------+---------+-----------+
  36. |docstring |5      |20.83 |5        |=          |
  37. +----------+-------+------+---------+-----------+
  38. |comment   |2      |8.33  |17       |-15.00     |
  39. +----------+-------+------+---------+-----------+
  40. |empty     |2      |8.33  |3        |-1.00      |
  41. +----------+-------+------+---------+-----------+
  42. Duplication
  43. -----------
  44. +-------------------------+------+---------+-----------+
  45. |                         |now   |previous |difference |
  46. +=========================+======+=========+===========+
  47. |nb duplicated lines      |0     |0        |=          |
  48. +-------------------------+------+---------+-----------+
  49. |percent duplicated lines |0.000 |0.000    |=          |
  50. +-------------------------+------+---------+-----------+
  51. Messages by category
  52. --------------------
  53. +-----------+-------+---------+-----------+
  54. |type       |number |previous |difference |
  55. +===========+=======+=========+===========+
  56. |convention |4      |6        |-2.00      |
  57. +-----------+-------+---------+-----------+
  58. |refactor   |0      |0        |=          |
  59. +-----------+-------+---------+-----------+
  60. |warning    |0      |0        |=          |
  61. +-----------+-------+---------+-----------+
  62. |error      |0      |0        |=          |
  63. +-----------+-------+---------+-----------+
  64. Messages
  65. --------
  66. +----------------------+------------+
  67. |message id            |occurrences |
  68. +======================+============+
  69. |bad-whitespace        |2           |
  70. +----------------------+------------+
  71. |missing-final-newline |1           |
  72. +----------------------+------------+
  73. |invalid-name          |1           |
  74. +----------------------+------------+
  75. Global evaluation
  76. -----------------
  77. Your code has been rated at 6.92/10 (previous run: 5.38/10, +1.54)

‘’‘’Report

=======‘’‘’以上是Pylint对程序的建议,以下都是报告内容。多数时候,我们其实并不想看那么冗长的报告。这时候,体贴的Pylint就让我们屏蔽掉它们。

加上参数 --reports=n 或者更简单写成 -rn 就好了。再看检查结果:

  1. c:\>c:\Python27\Scripts\pylint.exe --reports=n d:\workspace\PyComm\src\Interview
  2. s\yanghui.py
  3. No config file found, using default configuration
  4. ************* Module Interviews.yanghui
  5. C: 19, 0: Exactly one space required after comma
  6. for j in range(1,i):    #中间元素
  7. ^ (bad-whitespace)
  8. C: 21, 0: Exactly one space required after comma
  9. YHTriangle[i].insert(j,YHTriangle[i-1][j-1] + YHTriangle[i-1][j]
  10. )
  11. ^ (bad-whitespace)
  12. C: 23, 0: Final newline missing (missing-final-newline)
  13. C: 11, 0: Invalid constant name "YHTriangle" (invalid-name)

建议分三种:“bad-whitespace”, "missing-final-newline", "invalid-name".

前两个好说,加空格,加空行。但是下面这个怎么破?

  1. C: 11, 0: Invalid constant name "YHTriangle" (invalid-name)

命名不规范?认为是个constant值? 其实可以把这类问题忽略掉。

“Invalid constant name” 错误号是 C0103,所以加上 --disable=C0103即可。

  1. c:\>c:\Python27\Scripts\pylint.exe --reports=n --disable=c0103 d:\workspace\PyCo
  2. mm\src\Interviews\yanghui.py
  3. No config file found, using default configuration

没输出就是说名没问题了。

当然,还有更多的参数可以供选择。

=======================华丽丽的分割线===============================

平时写Python,我们几乎都不直接用命令行,而是用集成的IDE工具。比如猫哥常用的PyCharm。

Pylint官方文档提了可以支持PyCharm不过太简略了。

实际操作是这样的:

进入PyCharm,从菜单栏,依次进入: File -> Settings -> Tools -> External Tools。

“+”,进行添加。需要填写的部分分别是:“Name”,“Tool Settings -> Programs”、“Tool
Settings -> Parameters”、“Tool Settings -> Working directory”。

用Pylint规范化Python代码,附PyCharm配置

注意:

“Parameters”里其它参数不管怎么写,必须在最后加上$FilePath$,“Working directory”里必须写
$FileDir

另外,需要再添加“Output Filter”,在上图中间靠右。填写内容的“Regular expression to match output”,必须是:$FILE_PATH$:$LINE$:
最后那个是冒号。

用Pylint规范化Python代码,附PyCharm配置

配置完毕,选择一个Python程序,右键点击,快捷菜单中会有“Extensions Tools -> Pylint”,点击运行即可。输出结果在执行程序结果的窗口(IDE下半部分)。

如果看到返回值为0,说明程序没问题了。

    1. C:\Python27\Scripts\pylint.exe --reports=n --disable=C0103 D:\PyCharmSpace\test1\test1\hello.py
    2. No config file found, using default configuration
    3. Process finished with exit code 0