Pylint使用教程

  一、导言

                                                                                   ..;fxxx?.
                                                                                .^1xf;.  .fn.
                                                                               .jx:.      .r.
                                                                             .fj '       .?n.
                                                                            'f) .     ..trf`.
                         .'.'                                              >x.      !xn} .
                        :r';"                                             }j     .`x)'
             .       ..rx ..j.                                          .)x..   .fx`.
          .rux.    . fn.  ..n`                                          .x` .  .jf
          .n.tj..  .f{.    .x.                                        .'x^    'ff.
          /j. nurc1-..     ./f/ .                                      :r.    :r.
          fl.zcJJJJY        ...!j1                                    .j!    .x..
          fczJJJJJJU           . in~.                                 .x..  .\j
        . xXJJYCJUJC              .fx.                               .>j   .'n.
        .jYJJCli!?!i..             .jr.                              .xj  ..rj.
       ./XJJJJi!!!!i!               .jf'                             .n'   .x'
       'cJJJJLi!!!!i.                'n^.                            .x.   jt.
       tzJJU!!!!!i!.                  'tjf(.   '.^)jrrrrx|; .       'x'. .;n.
      'nYJJQii`iii                      .`|..nnzzzJCJUUJJU[rnux/ ..lr".  ln .
      .nJJL.     l.                     .j<zcJJJJUJJJJJJC!!!!iilnv\    .\n..
       nn`      ,vr.                  ../tYJJJJJJJJJililli!!!!!!i>jf...nj .
      .n.      .jn.                   ..}.YCJJUCJCJ!!!!!!!!!!!!!!!!I'zx .
       xl.       ..                  .'t...i!!!tJJ!!!!!!!!!!!!!!!!!!..fj..
      .x\.'      `)(+. . .            f   .i!!!i .!!!!!!!!!!i:.i!!!!  . x^.
      .j .j        ;<; ..           .t" .  .. .' ..`i'!;"'.^'  .'l;...   x~.
     .j...t.       '    ..       .../                                   ..x'.
      /f..-        .`t..         .).      日期: 20231025                  ,r.
      .xj             .-       '..                                        'x
       . xj..                                                              j.
          'txxj~ ^.                                                     ...?xrrr`'
             .'.`ff/..            二狗大爷出品  MEOW!              ..   .!!!!!,.`jt.
                 .^|f'.                                         .UJJJJc!!!!!!i. .fr..
                 .t' x:.                                       .UJJJJJ!i!!!!!!I  . xr.
              .'f[.  .j\.....                                   JJJJJJJ!X>!!!i.    .^fx..
             .,r      .:j!/.          '..                   .../\YJJJJJJJCv!l'....     f.
           . j).       .<r           ./t^              . .!rvxf. ixzcXXYUYzcr^>xncx}'.?j.
          .)r.        .vt'         .~n-..... ."~\jjxnxxxxfI'      .. .  .  .    .'. I?;.
         .xI.     .')nX,.        ',xj...'l_]_<".....
       `j/ .   ..<rxrr..       ..nr.
     .\j..   ..jrl\n..       .>xj.'
   \jf.    .jnj..j\'.     ../xf'.
   t'. '.]xn. `rx        .xn-.
   .{^+tj.. .rx'     ..tnx...
          /f'..    '{xj
          "jl.  .~jj..
           ..)))"..

Pylint是一个Python源代码静态分析工具,用于检查Python代码的质量、风格和错误。它可以帮助开发者识别潜在的问题并提供代码改进建议。本文是Pylint的工具说明,包括工具说明、安装方法、使用示例和注意事项。

  Pylint是一个开源工具,它执行静态代码分析,检查Python代码的一致性、规范性和错误。它使用不同的插件和规则来评估代码,并生成相应的分数和建议,以改善代码质量。

  三、安装和配置

  有四种安装方式

  3.1 作为命令行工具

  使用pip安装Pylint(确保你已经安装了Python):

pip install pylint

  使用conda或apt 

sudo apt-get install pylint
conda install pylint

  3.2 编辑器或IDE集成(见专栏文章后续更新)

  3.3 预提交集成工具

  配置文件 .pre-commit-config.yaml

- repo: local  
  hooks:    
  - id: pylint      
    name: pylint      
    entry: pylint      
    language: system      
    types: [python]      
    args:  ["-rn", # Only display messages         
            "-sn", # Don't display the score         
            "--rcfile=pylintrc", # Link to your config file        
            "--load-plugins=pylint.extensions.docparams", # Load an extension      
          ]

  3.4 多版本解释器集成

  即可使用不同版本的解释器来相互检查,例如python3.8和pylint来检查python3.5版本的代码

  四、主要功能和用法

  4.1 开始

  help 参数来查看可用参数的概念:

pylint --help

Commands:
    --help-msg=<msg-id>
    --generate-toml-config
Messages 
control:
    --disable=<msg-ids>
Reports:
    --reports=<y or n>
    --output-format=<format>

  Long-help 参数查看更多细节

pylint --long-help

Output:
   Using the default text output, the message format is :
  MESSAGE_TYPE: LINE_NUM:[OBJECT:] MESSAGE
  There are 5 kind of message types :
  * (C) convention, for programming standard violation
  * (R) refactor, for bad code smell
  * (W) warning, for python specific problems
  * (E) error, for probable bugs in the code
  * (F) fatal, if an error occurred which prevented pylint from doing
  further processing.

  4.2 用法

  用法:在终端或命令提示符中运行 Pylint,将 your_python_file.py 替换为你要检查的 Python 文件的路径

pylint your_python_file.py

  同时,上述路径可以使用以下所有目标进行替换

  1. path:relative path to the file

  2. abspath:absolute path to the file

  3. line:line number

  4. column:column number

  5. end_line:line number of the end of the node

  6. end_column:column number of the end of the node

  7. module:module name

  8. obj:object within the module (if any)

  9. msg:text of the message

  10. msg_id:the message code (eg. I0011)

  11. symbol:symbolic name of the message (eg. locally-disabled)

  12. C:one letter indication of the message category

  13. category:fullname of the message category

  4.3 退出代码;程式终止码

exit code

meaning

0

no error

1

fatal message issued

2

error message issued

4

warning message issued

8

refactor message issued

16

convention message issued

32

usage error

  4.4 报错检索

  https://pylint.pycqa.org/en/latest/user_guide/messages/messages_overview.html

  五、实践案例和代码示例

  假设使用pylint检查的脚本文件代码名为 simpleecesar.py,代码内容如下:

#!/usr/bin/env python3
import string
shift = 3
choice = input("would you like to encode or decode?")
word = input("Please enter text")
letters = string.ascii_letters + string.punctuation + string.digits
encoded = ""
if choice == "encode":
    for letter in word:
        if letter == " ":
            encoded = encoded + " "
        else:
            x = letters.index(letter) + shift
            encoded = encoded + letters[x]
if choice == "decode":
    for letter in word:
        if letter == " ":
            encoded = encoded + " "
        else:
            x = letters.index(letter) - shift
            encoded = encoded + letters[x]
print(encoded)

终端返回如下:

tutor Desktop$ pylint simplecaesar.py
************* Module simplecaesarsimplecaesar.py:1:0: C0114: Missing module docstring (missing-module-docstring)
simplecaesar.py:5:0: C0103: Constant name "shift" doesn't conform to UPPER_CASE naming style (invalid-name)simplecaesar.py:8:0: C0103: Constant name "letters" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:9:0: C0103: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)simplecaesar.py:13:12: C0103: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:15:12: C0103: Constant name "x" doesn't conform to UPPER_CASE naming style (invalid-name)simplecaesar.py:16:12: C0103: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:20:12: C0103: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)simplecaesar.py:22:12: C0103: Constant name "x" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:23:12: C0103: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)-----------------------------------Your code has been rated at 4.74/10

  其中

"simplecaesar.py:1:0: C0114: Missing module docstring (missing-module-docstring)"

  表示,被检查的脚本缺少docstring内容,即脚本说明内容,补充更新该代码后如下

#!/usr/bin/env python3

"""This script prompts a user to enter a message to encode or decodeusing a classic Caesar shift substitution (3 letter shift)"""

import string
shift = 3
choice = input("would you like to encode or decode?")
word = input("Please enter text")
letters = string.ascii_letters + string.punctuation + string.digits
encoded = ""

if choice == "encode":
    for letter in word:
        if letter == " ":
            encoded = encoded + " "
        else:
            x = letters.index(letter) + shift
            encoded = encoded + letters[x]
if choice == "decode":
    for letter in word:
        if letter == " ":
            encoded = encoded + " "
        else:
            x = letters.index(letter) - shift
            encoded = encoded + letters[x]

print(encoded)

再次运行pylint simplecaesar.py后

tutor Desktop$ pylint simplecaesar.py
************* Module simplecaesar
simplecaesar.py:8:0: C0103: Constant name "shift" doesn't conform to UPPER_CASE naming style (invalid-name)simplecaesar.py:11:0: C0103: Constant name "letters" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:12:0: C0103: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)simplecaesar.py:16:12: C0103: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:18:12: C0103: Constant name "x" doesn't conform to UPPER_CASE naming style (invalid-name)simplecaesar.py:19:12: C0103: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:23:12: C0103: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)simplecaesar.py:25:12: C0103: Constant name "x" doesn't conform to UPPER_CASE naming style (invalid-name)
simplecaesar.py:26:12: C0103: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)------------------------------------------------------------------Your code has been rated at 5.26/10 (previous run: 4.74/10, +0.53)

  漂亮!Pylint 告诉我们,自上次运行以来,我们的代码评级有了多大的提高,现在只剩下无效名称消息了。

  对于实例变量、函数、类等等的命名,有相当明确的约定。约定的重点是使用大写和小写,以及在名称中分隔多个单词的字符。这很适合通过正则表达式进行检查,因此应该匹配(([ A-Z _ ][ A-Z1-9 _ ] ) | (_ 。( _)) $.

  在这种情况下,Pylint 告诉我们,这些变量似乎是常量,应该都是大写。这是一个从一开始就与 Pylint 共存的内部约定。您也可以创建自己的内部命名约定,但为了本教程的目的,我们希望坚持 PEP 8标准。在这种情况下,我们声明的变量应该遵循所有小写字母的约定。适当的规则类似于: “应该匹配[ a-z _ ][ a-z0-9 _ ]{2,30} $”。注意正则表达式中的小写字母(A-Z 与 A-Z)。

  六、注意事项

  • Pylint 的检查结果包括了对代码风格、规范性和潜在问题的检查,但不一定意味着所有输出都需要立即处理。有些问题可能并不重要,你可以根据项目需求和团队规则来决定哪些问题需要处理。

  • 你可以使用 Pylint 配置文件来自定义检查规则和忽略特定的检查。这有助于将 Pylint 集成到项目中,并确保符合团队的代码规范。

  • Pylint 提供了广泛的命令行选项和配置选项,你可以使用 pylint --generate-rcfile 生成一个示例配置文件,然后进行自定义设置。

  • 可以在集成开发环境(IDE)中安装 Pylint 插件,以便在编写代码时实时检查问题。

 

  七、结论

  Pylint 是一个有用的工具,可以帮助你提高 Python 代码的质量和一致性,但在使用时需要根据项目需求和团队规则来决定如何处理检查结果。

  参考文档

  https://pylint.pycqa.org/en/latest/tutorial.html

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值