Saturday, June 1, 2013

Debugging Python programs in GDB

The instructions at http://wiki.python.org/moin/DebuggingWithGdb 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 debug_me.py:

python-dbg debug_me.py &

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
   2    
   3    
   4    def debug_me():
   5        for i in xrange(10000):
   6            print i
  >7            time.sleep(5)
   8    
   9    
  10    debug_me()

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

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

(gdb) py-bt
#5 Frame 0x2852f20, for file /tmp/debug_me.py, line 7, in debug_me (i=2)
    time.sleep(5)
(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 https://wiki.ubuntu.com/PyDbgBuilds)

1 comment:

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

    ReplyDelete