Debugging your Cython program
Cython comes with an extension for the GNU Debugger that helps users debug Cython code. To use this functionality, you will need to install gdb 7.2 or higher, build with Python support (linked to Python 2.5 or higher).
The debugger will need debug information that the Cython compiler can export.
This can be achieved from within the setup
script by passing
pyrex_debug=True to your Cython Extenion class:
from Cython.Distutils import extension ext = extension.Extension('source', 'source.pyx', pyrex_debug=True) setup(..., ext_modules=[ext)]
With this approach debug information can be enabled on a per-module basis.
Another (easier) way is to simply pass the
--pyrex-debug flag as a command
python setup.py build_ext --pyrex-debug
For development it's often easy to use the
--inplace flag also, which makes
distutils build your project "in place", i.e., not in a separate build
When invoking Cython from the command line directly you can have it write
debug information using the
cython --debug myfile.pyx
The debugger is new in the upcoming release of Cython, 0.13.1. Currently, it can be cloned from hg.cython.org/cython-gdb.
Running the Debugger
To run the Cython debugger and have it import the debug information exported
by Cython, run
cygdb in the build directory:
$ python setup.py build_ext --pyrex-debug --inplace $ cygdb GNU gdb (GDB) 7.2 ... (gdb)
When using the Cython debugger, it's preferable that you build and run your code
with an interpreter that is compiled with debugging symbols (i.e. configured
--with-pydebug or compiled with the
-g CFLAG). If your Python is
installed and managed by your package manager you probably need to install debug
support separately, e.g. for ubuntu:
$ sudo apt-get install python-dbg $ python-dbg setup.py build_ext --pyrex-debug --inplace
Then you need to run your script with
You can also pass additional arguments to gdb:
$ cygdb /path/to/build/directory/ GDBARGS
$ cygdb . --args python-dbg mainscript.py
To tell cygdb not to import any debug information, supply
-- as the first
$ cygdb --
Using the Debugger
The Cython debugger comes with a set of commands that support breakpoints, stack inspection, source code listing, stepping, stepping over, etc. Most of these commands are analogous to their respective gdb command.
The following functions are gdb functions, which means they can be used in a gdb expression.
(gdb) print $cy_cname("x") $1 = "__pyx_v_x" (gdb) watch $cy_cvalue("x") Hardware watchpoint 13: $cy_cvalue("x") (gdb) print $cy_lineno() $2 = 12
Configuring the Debugger
A few aspects of the debugger are configurable with gdb parameters. For instance, colors can be disabled, the terminal background color and breakpoint autocompletion can be configured.
This is how these parameters can be used:
(gdb) set cy_complete_unqualified off (gdb) set cy_terminal_background_color light (gdb) show cy_colorize_code