Python static Check tool

Source: Internet
Author: User

Python is a dynamic language. There is no strict type restriction when passing parameters to Python. When writing a Python program, it is often found that errors can only be found at execution time. There are some errors due to hidden deep, only the specific logic will trigger, often resulting in the need to spend a lot of time to get the syntax errors to slowly troubleshoot. In fact, there are some errors are very obvious, if you can write a program to find these errors, you can improve work efficiency.

Note: It is customary to compile languages such as C + +, and use dynamic language like Python, always a bit not at ease, especially when building a relatively large system. The Python static grammar checker appears.

Pyflakes (Error Detection Tool)

Pyflakes: Https://pypi.python.org/pypi/pyflakes

A simple program for checking python source file errors.

Pyflakes Analyze the program and check for various errors. It is implemented by parsing the source file without importing it, so it is safe to use in the module without any side effects. It's pretty fast, too.

Installation

Quick installation method: Pip Installpyflakes

There are two ways you can use Pyflakes:

Command line use

Command-line usage:

Pyflakes *.py

Vim Configuration

The second way: the configuration of the Vim editor, first vim must support whether Python,vim support Python is checked using the following method.

Vim

#进入vim编辑器界面之后, enter the following command in command-line mode

: Version

Vim-vi Improved 7.3 (2010Aug, compiled Oct 27 2010 17:51:38)

Ms-windows 32-bit console version

Includes patches: 1-46

compiler [email protected]

The large version has no graphical interface. You can use (+) and not use (-) Features:

+arabic +autocmd-balloon_eval-browse ++builtin_terms +byte_offset +cindent

+clientserver +clipboard+cmdline_compl +cmdline_hist +cmdline_info +comments

+conceal +CRYPTV +cscope+cursorbind +cursorshape +dialog_con +diff +digraphs-dn

-ebcdic +emacs_tags +eval+ex_extra +extra_search +farsi +file_in_path

+find_in_path +float+folding-footer +gettext/dyn-hangul_input +iconv/dyn

+insert_expand +jumplist+keymap +langmap +libcall +linebreak +lispindent +LISTCM

+localmap-lua +menu +mksession +modify_fname+mouse-mouseshape +multi_byte

+multi_lang-mzscheme-netbeans_intg-osfiletype +path_extra-perl +persistent_un

-postscript +printer-profile-python-python3+quickfix +reltime +rightleft-ru

+scrollbind +signs +smartindent-sniff+startuptime +statusline-sun_workshop

+syntax +tag_binary+tag_old_static-tag_any_white-tcl-tgetent-termresponse

+textobjects +title-toolbar+user_commands +vertsplit +virtualedit +visual

+visualextra +viminfo+vreplace +wildignore +wildmenu +windows +writebackup

-xfontset-xim-xterm_save-xpm_w32

Where the + number represents support,-the number indicates that it is not supported. So the above vim does not support python, so you need to upgrade your VIM! Here we configure VIM to support the pyflakes.

First, download the Pyflakes.vim and unzip it into the Vim configuration folder, for example: Copy directly below the/etc/vim/folder.

Then, modify the Vim configuration, open VIMRC, configure the following options:

Ifhas ("Autocmd")

FileType plugin indent on

endif

Flake8 (Code specification Tool) Overview

Flake8 is a package of the following three tools:

1) pyflakes

2) PEP8

3) Nedbatchelder ' s McCabe script

Flake8: Https://pypi.python.org/pypi/flake8, the advantage is extensible.

Flake8 runs all the tools by starting a separate Flake8 script, which displays alarms in a per file and merges them into the output.

Also adds some features:

1) The file containing this line will be ignored: #flake8: Noqa

2) The line ending with the #noqa comment will not be issued by the notice police

3) git and mercurial hooks

4) McCabe Complexity Checker

5) can be extended via Flake8.extension entry point

Installation

Download source after decompression to install: pythonsetup.py Install

Quick installation: Pipinstall Flake8

Use

In order to run Flake8, it needs to be raised in any directory or Python module.

$ Flake8 Coolproject

Coolproject/mod.py:97:1: F401 ' shutil ' imported but unused

coolproject/mod.py:625:17:e225 Missingwhitespace around Operato

Coolproject/mod.py:729:1: F811 redefinitionof function ' readlines ' from line 723

Coolproject/mod.py:1028:1: F841 localvariable ' Errors ' is assigned-but never used

The output of Pyflakes and PEP8 (and optional plug-ins) will be merged together to return.

Flake8 provides an extended option:--max-complexity, if the McCabe complexity of the function is higher than the given value, an alarm is emitted. It is not activated by default.

$ Flake8--max-complexity Coolproject

Coolproject/mod.py:97:1: F401 ' shutil ' imported but unused

coolproject/mod.py:625:17:e225 missingwhitespace around operator

Coolproject/mod.py:729:1: F811 redefinitionof unused ' readlines ' from line 723

Coolproject/mod.py:939:1: C901 ' Checker.check_all ' is too complex (12)

Coolproject/mod.py:1028:1: F841 localvariable ' Errors ' is assigned-but never used

Coolproject/mod.py:1204:1: C901 ' selftest ' is too complex (14)

This feature is useful for examining very complex code. According to McCabe, any code below 10 is too complex.

Vim Configuration

If you want to use Flake8 in vim, install it using Vundle.

"Flake8 plugin for Vim.

Bundle ' Nvie/vim-flake8 '

"Compiler plugin for Python stylechecking tool.

Bundle ' Vim-scripts/pylint.vim '

Autocmd FileType python compiler pylint

Vundle's official website: https://github.com/gmarik/vundle

Easy to use VIMRC, download the following method:

git clone https://github.com/icocoa/icocoa-vimrc.git--recursive VIMRC//Icocoa is my another account in GitHub

Pychecker

Official website: http://pychecker.sourceforge.net/

http://sourceforge.net/projects/pychecker/

Https://pypi.python.org/pypi/PyChecker

Overview

Pychecker is a static analysis tool for Python code that can help you find bugs in Python code and can warn you about the complexity and format of your code.

Pychecker can work in a variety of ways. First, Pychecker will import the modules contained in the checked file, check that the import is correct, and examine the functions, classes, and methods in the file.

Pychecker can be checked out by the following types of problems:

1) Global volume not found, such as no import module

2) Wrong number of arguments passed to the function, method, constructor

3) Wrong number of arguments passed to the built-in functions and methods

4) String formatting information does not match

5) Use of non-existent class methods and properties

6) Change of signature when overriding function

7) Redefine functions, classes, methods in the same scope

8) use of uninitialized variables

9) The first argument of a method is not self

10) unused global and local quantities (modules or variables)

11) parameters of unused functions/methods (not including self)

12) No docstring in modules, classes, functions, and methods

Installation

After downloading the latest version of Pychecker from the official website, unzip the installation:

Python Setup.pyinstall

Basic use

pycheckersetup.py

Use the--only parameter to check only the syntax of your own.

Pychecker--onlysetup.py

Parameters and Options Description: pychecker[options] file1.py file2.py ...

--only only a warning to the command-line file, default is no

-#,--limit maximum number of warnings displayed, default is 10

--no-shadowbuiltin Check if there are variables covered by the built-in variables, default to OFF

-q,--stdlib ignore file warnings for standard libraries, default to OFF

-t,--argsused keywords for unused methods/functions, default to On

Configuration

Modify the default configuration and behavior: the. pycheckrc file, which is placed in the $home directory,--rcfile option to generate a copy of the default configuration file.

To suppress the warning information for some modules/functions/classes/methods, you can define a forbidden dictionary in the. pycheckrc file, similar to the following: "Module", "Module.function", "Module.class", and so on.

or define it directly in your code:

__pychecker__ = ' No-namedargs maxreturns=0 unsednames=foo,bar '

Where the value in the __pychecker__ format is the same as the value in the Forbidden dictionary.

Import the Pychecker module into the code file and use:

Importpychecker.checker

This will check all modules that were imported after pychecker, without checking.

If you cannot pass command-line arguments, you can use:

os.environ[' pychecker ']= ' command line options here '

Equivalent to setting pychecker in the shell environment:

Pychecker= ' no-namedargsmaxreturns=0 '/path/to/your/program

To turn off the warning, you can add the following before importing Pychecker:

os.environ[' pychecker_disabled ']= 1

Equivalent to setting pychecker_disabled in the shell environment:

Pychecker_disabled=1/path/to/your/program

Pylint (recommended)

Pylint: Https://pypi.python.org/pypi/pylint

Pylint's official website: http://www.pylint.org/

Overview

Pylint is a python source code parser that looks for programming errors, helps execute a code standard, and sniffs some code flavors.

By default, Pylint enables a number of rules. It is highly configurable and controls it from within the code's internal handlers. In addition, it is possible to write plug-ins to add to your own checks.

Note: Compared to Pychecker,pylint is a high-level Python Code analysis tool that parses errors in Python code, finds code style standards that do not conform to code (pylint the code style used by default is PEP 8), and potentially problematic codes. Currently the latest version of Pylint is pylint-1.2.1. You can check the length of a line of code, whether variable names conform to specifications, and so on. Run two times to see if the code is improved, whether the score has improved, 10 points out.

Pylint is a Python Code analysis tool that parses errors in Python code to find code style standards that are not compliant (the code style used by Pylint is PEP 8, specific information, see Resources), and potentially problematic code.

1) Pylint is a Python tool that provides additional functionality in addition to the usual Code analysis tools: Checking the length of a line of code, whether a variable name conforms to a naming standard, whether a declared interface is actually implemented, and so on.

2) One of the great benefits of Pylint is its high configuration, high customization, and the ability to write small plugins to add functionality.

3) If you run the Pylint two times, it will show both the current and last run results, so you can see if the code quality has been improved.

4) Pylint is also integrated in the eclipse's Pydev plugin.

Pylint requires astroid (newer and better) and Logilab-common (version >= 0.53) packages.

Https://bitbucket.org/logilab/astroid

Http://www.logilab.org/projects/common

Installation

Install from the source release, unzip the TAR package and run:

Python setup.py Install

Quick installation Method: Pipinstall Pylint

You must use a similar method to install dependencies. For Debian and RPM installation packages, use your common tools based on your Linux distribution.

The syntax checker for Python in Pydev uses Pylint, which is the following points to note:

1) Install logilab-asting and Logilab-common first.

2) then to make the two packages work properly, do some action on Logilab-common:

proc.py Line (115)

Fromsignal Import * #signal, SIGXCPU, SIGKILL, SIGUSR2, SIGUSR1

Fromos Import * #killpg, Getpid, SETPGRP

Fromthreading import Timer, CurrentThread, Thread, Event

FromTime Import Time

#from Resource Import Getrlimit, SETRLIMIT,RLIMIT_CPU, rlimit_as

Description of the error message

(C) practice. Violates coding style standards

(R) refactoring. Code that was badly written.

(W) warning. Some Python-specific issues.

(E) error. Most likely an error in the code.

(F) Fatal error. Errors that prevent Pylint from running further.

Run

To invoke Pylint from the command line, use the following method:

pylint [Options] Module_or_package

You should pass the name of a Python package or module to Pylint. Pylint will import the package or module, so you should be aware of your pythonpath, as it is a common error Analysis module installation version, not a development version.

You can also parse Python files, but there are some limitations. Remember that Pylint will attempt to convert the file name to the module name and only succeed to process the file.

Python static Check tool

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.