Tools for Python programming

From GRASS-Wiki
Revision as of 04:57, 7 February 2013 by Wenzeslaus (talk | contribs) (pylint, pep8, cprofile, pyreverse, spyder)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

To help with finding broken code, unused variables and other problems, there are several tools available. Described tools are free and open source and usually widely available in GNU/Linux distribution repositories or through pip. They can be connected to some code editor or run separately from command line. Some editors integrate some of these tools. Generally, all tools need to be run from a GRASS session.

pep8

Checks the basic correctness of Python code according to PEP 8 -- Style Guide for Python Code.

pep8 lmgr/toolbars.py

Pylint

Main article: Pylint rc file for GRASS

Pylint is a tool for static source code analysis. It provides wide range of analysis and is highly customizable. It is integrated to some Python editors.

cProfile

cProfile is a Python profiling tool. It can be used directly in your Python source code or from the command line. The output can be processed by the gprof2dot tool which generates call graph in dot (depends on Graphviz is necessary to render the graph).

For Ubuntu, Graphviz and cProfile are available in repository (graphviz and python-profiler packages). gprof2dot tool needs to be installed through pip (sudo pip install gprof2dot).

# does the actual profiling
python -m cProfile -o output.pstats  my_python_script.py --various-my-script-parameters foo bar

# creates a callgraph with profiling info (filtered)
gprof2dot -f pstats output.pstats | dot -Tpng -o gprof2dot_output.png
#!/bin/bash

# Usage:
# ./python-profile.sh your_python_script.py and its parameters
# need to run in the directory which contains profiled script 

OUTFILE=$(basename $1 .py)_profile

python -m cProfile -o $OUTFILE.pstats $* \
&& gprof2dot -f pstats $OUTFILE.pstats > $OUTFILE.dot \
&& dot -Tpng -o $OUTFILE.png $OUTFILE.dot \
&& dot -Tpdf -o $OUTFILE.pdf $OUTFILE.dot

Pyreverse

Needs to run in distribution directory.

Note that it exploits only import and usage dependencies. Because of the Python dynamic typing it is not possible to find dependency on particular object interface when the object is not created but only passed to a function or object constructor.

cd dist.../etc/gui/wxpython
pyreverse -o pdf -p wxgui --only-classnames core/ gui_core/ lmgr/ mapdisp/

Spyder

To get proper results, you should run it form the GRASS session. It has integrated pylint tool. Bugs and requests can be reported here: https://code.google.com/p/spyderlib/.