Wednesday, June 9, 2010

debugging python script in ipython

ipython doesn't work with built-in pdb debugger. While I tried to debug a python script with "run -d script.py" within ipython shell, I got bellow error:
AttributeError: Pdb instance has no attribute 'curframe'

To debug script in ipython, we need to use a different debugger, pydb, for example. There are only three steps to setup and use it.
  1. download and install pydb.
  2. start ipython with -pydb argument: ipython -pydb
  3. start debugging with: run -d script.py
It's mandatory to set HOME environment variable to use pydb. On my windows box, there is no HOME environment variable set by default, and I got bellow error:
KeyError: 'HOME'
It can be solved by adding HOME environment variable.

Because pydb use the same set of commands with gdb, it's fairly straightforward to get start with it if you have done some debugging in gdb. This is one reason why I pick it as my debugger.

Reference:
Introducing the pydb Debugger
Debugging in Python

3 comments:

rocky said...

In the long-term, pydb is being phased out in favor of pydbgr.

Here is how you can run pydbgr from inside ipython.

Note: this works on the svn trunk and not versions less than pydbg-0.1.4 soon to be released.

From the pydbgr distribution there is a file called ipython/ipy_pydbgr.py. Copy that to the IPython configuration directory. Typically this is called ~/.ipython, but it can be set using the -ipythondir option or the IPYTHONDIR environment variable.

Here is an example:

$ cd ~/.ipython
$ wget http://pydbgr.googlecode.com/svn/trunk/ipython/ipy_pydbgr.py ipy_pydbgr.py

Now go into ipython and "import ipy_pydbgr":

$ ipython
IN [1]: import ipy_pydbgr

Magic function %pydbgr will get added, and you can use that to call the debugger.

IN [2]: %pydbgr /tmp/python_program_to_debug.py opt1 opt2

Note that you enter a Python file name. Don't use quotes around the filename nor parenthesis after %pydbgr or commas between command options. Running %pydbgr like issuing a command from a command line.

If the above works you may want to add the "import ipy_pydbgr" to your ipy_user_conf.py file.

Unknown said...

Thanks for your information, and you guys' fantastic work.

I noticed pydbgr on pydb's homepage too. I also noticed it's replacing pydb. So I hesitated for a while about whether to use pydb or pydbgr. Finally I chose pydb because it seemed more popular, though I understood using pydbgr would be the trend.

My suggestion is besides listing pydbgr's powerful features, would you please make a standalone wiki page showing the advantages of pydbgr over pydb? Being able to understand the advantages from the perspective of pydb will increase the chance of people choosing pydbgr, since pydb is already so popular and famous.

rocky said...

Ok. I have added an issue to remind me. Thanks for the suggestion.