Tuesday, July 21, 2009

Python Debugger

I thought I will document this somewhere in case its useful to anyone.

I recently had to do some work with the python debugger which is cool, but does not support any command line completion or even a history. I googled and apparently you can use ipython as a debugger but I could not get it to work properly.

I found some code on the net to do completion and I added a bit of history. To do this you need to add the following files:

~/.pdbrc.py:
import os.path, os 

# save this in .pdbrc.py in your home directory
def complete(self, text, state):
"""return the next possible completion for text, using the current frame's
local namespace

This is called successively with state == 0, 1, 2, ... until it
returns None. The completion should begin with 'text'.
"""
try:
        import rlcompleter
        # keep a completer class, and make sure that it uses the current local scope  
if not hasattr(self, 'completer'):
self.completer = rlcompleter.Completer(self.curframe.f_locals)
else:
self.completer.namespace = self.curframe.f_locals
return self.completer.complete(text, state)
except Exception,e:
print e

and ~/.pdbrc
# save this in .pdbrc in your home directory 
import os
import sys
# import rlcompleter early, as it contains side effects
import rlcompleter
# refresh the terminal
os.system("stty sane")
# this rc file takes single lines, so define our complete function here
execfile(os.path.expanduser("~/.pdbrc.py"))
# replace the Pdb class's complete method with ours
sys._getframe(1).f_globals['Pdb'].complete = complete
# set use_rawinput to 1 as tab completion relies on rawinput being used
sys._getframe(1).f_locals['self'].use_rawinput = 1


No comments: