Saturday, June 1, 2013

Debugging Python programs in GDB

The instructions at make it seem complicated, but it turns out to be very simple in Ubuntu 12.04 to use the GDB to debug Python code. The downside is that you have to run the Python program themselves with an interpreter compiled with the symbols in order to take advantage of this functionality.

If you're using Ubuntu 12.04, you can use the following apt-get install:
sudo apt-get install python-dbg

Suppose we had a Python program called

python-dbg &

To attach to the process, you would do:

gdb python-dbg [Python PID]

The commands that you could use are (help py-)

(gdb) py-list
   4    def debug_me():
   5        for i in xrange(10000):
   6            print i
  >7            time.sleep(5)
  10    debug_me()

(gdb) py-up
#8 Frame 0x2195810, for file /tmp/, line 9, in <module> ()

(gdb) py-print i
local 'i' = 0

(gdb) py-bt
#5 Frame 0x2852f20, for file /tmp/, line 7, in debug_me (i=2)
(gdb) py-print i
local 'i' = 2
(gdb) py-locals 
i = 2

You can also use standard GDB commands but any C extensions must also be compiled with the debugging symbols too! For more info, check out the file installed in /usr/share/doc/python2.7-dbg/README.debug (or alternativly at

1 comment:

  1. Thanks for the tutorial Roger. It was very informative and useful.