代码分析工具python_Python代码分析工具:PyChecker、Pylint
1 概述
PyChecker是Python代碼的靜態分析工具,它能夠幫助查找Python代碼的bug,而且能夠對代碼的復雜度和格式等提出警告。
PyChecker可以工作在多種方式之下。首先,PyChecker會導入所檢查文件中包含的模塊,檢查導入是否正確,同時檢查文件中的函數、類和方法等。
推薦閱讀:
PyChecker可以檢查出來的問題有如下幾種:
全局量沒有找到,比如沒有導入模塊
傳遞給函數、方法、構造器的參數數目錯誤
傳遞給內建函數和方法的參數數目錯誤
字符串格式化信息不匹配
使用不存在的類方法和屬性
覆蓋函數時改變了簽名
在同一作用域中重定義了函數、類、方法
使用未初始化的變量
方法的第一個參數不是self
未使用的全局量和本地量(模塊或變量)
未使用的函數/方法的參數(不包括self)
模塊、類、函數和方法中沒有docstring
2 使用
從官網下載最新版本的PyChecker之后,解壓安裝即可:python setup.py install
首先可以在解壓后的目錄中測試一番:
[root@rango pychecker-0.8.19]# pychecker setup.py
Processing module setup (setup.py)...
Warnings...
[system path]/distutils/command/bdist_wininst.py:271: Statement appears to have no effect
[system path]/distutils/command/build_scripts.py:80: No class attribute (dry_run) found
[system path]/distutils/command/build_scripts.py:97: No class attribute (dry_run) found
[system path]/distutils/command/build_scripts.py:120: (file) shadows builtin
[system path]/distutils/command/build_scripts.py:121: No class attribute (dry_run) found
[system path]/distutils/command/install_data.py:62: (dir) shadows builtin
[system path]/distutils/command/install_data.py:64: (dir) shadows builtin
[system path]/distutils/command/install_data.py:66: (dir) shadows builtin
[system path]/distutils/command/install_scripts.py:52: (file) shadows builtin
[system path]/distutils/command/install_scripts.py:53: No class attribute (dry_run) found
19 errors suppressed, use -#/--limit to increase the number of errors displayed
可以看到,檢查的結果將setup.py依賴的一些文件中的語法錯誤或者警告都列舉出來了,使用--only參數可以只檢查自身的語法問題:
[root@rango pychecker-0.8.19]# pychecker --only setup.py
Processing module setup (setup.py)...
Warnings...
None
參數和選項說明:pychecker [options] file1.py file2.py ...
--only? ? ? ? 只給出命令行的文件的警告,默認為no
-#,--limit? ? 顯示的最大警告數,默認為10
--no-shadowbuiltin? ? 檢查是否有變量覆蓋了內建變量,默認為off
-q,--stdlib? ? ? ? 忽略標準庫的文件的警告,默認為off
-T,--argSUSEd? ? 未使用的方法/函數的關鍵字,默認為on
修改默認配置和行為:.pycheckrc文件,該文件放置在$HOME目錄下,--rcfile選項可以生成一份默認的配置文件。
要禁止一些模塊/函數/類/方法的警告信息,可以在.pycheckrc文件中定義一個禁止字典,鍵類似:
‘module’,‘module.function’,'module.class'等。
或者直接在代碼中定義:
__pychecker__ = 'no-namedargs maxreturns=0 unsednames=foo,bar'
其中__pychecker__格式的值和在禁止字典中的值是一樣的
在代碼文件中導入PyChecker模塊及使用:
import pychecker.checker
這將會檢查所有在PyChecker之后導入的模塊,之前的不檢查。
如果不能傳遞命令行參數,可以使用:
os.environ['PYCHECKER'] = 'command line options here'
等價于在shell環境中設置PYCHECKER:
PYCHECKER='no-namedargs maxreturns=0' /path/to/your/program
要關閉警告,可以在導入PyChecker之前,加上:
os.environ['PYCHECKER_DISABLED'] = 1
等價于在shell環境中設置PYCHECKER_DISABLED:
PYCHECKER_DISABLED=1 /path/to/your/program
總結
以上是生活随笔為你收集整理的代码分析工具python_Python代码分析工具:PyChecker、Pylint的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python每行输出14个数_pytho
- 下一篇: 消极颓废的网名大全91个