Tuesday, April 12, 2011

Debugging Python on Emacs IDE

I've tried a few IDEs for standalone Python development. But end of the day I came back to Emacs. I love Emacs because it is lightweight, I can pretty much do whatever I can with any other IDE and much more if I write some Lisp script.

Here in this article, I'd just cover how to step through your standalone Python code and debug it using Emacs as the editor/IDE. First of all you have to install the following Emacs extension modules and Python debugging tools.
  • Install Pymacs from this github site and thank Fran├žois Pinard of Montreal for programming it
  • Install Rope and Ropemacs from here (using Mercury)
  • Check if you have PDB, just by typing it on command window (you'd mostly have)
Now the step-by-step debugging goes like this
  1. With your Python program on buffer, type M-x pdb. It would ask if you want to run PDB like, pdb a.out. Replace a.out with your Python module name. In the screenshot, it is adder.py (doing nothing useful).
  2. This opens a new PDB windows (Screenshot)
  3. Go to the lines where you need breakpoint, type C-x (you can notice the screenshot for the statement about it). If you are using Ubuntu, you get a very good look-n-feel, like that screenshot.
  4. Type c on the PDB buffer to run upto the breakpoint
  5. From the breakpoint, n for next line or s to explore into functions on that line. In Ubuntu, you'd have a GUI to assist you.
  6. To watch a variable, type p var, as in the screenshot.
  7. Any time during debugging, w prints out the stack and u and d lets you go up and down the stack.
For most of the standalone Python script, this would improve your productivity a lot. You can do more complex debug operations, but this is a very good start.

6 comments:

  1. Very useful, I've been racking my brain trying to devise a way to get this workflow working with an appengine app, but devappserver does something crazy that I haven't figured out yet so I have to jump over to pydev. which makes me sad every time I have to do it.

    ReplyDelete
  2. Cool!

    I don't think I've ever heard anyone describe Emacs as "lightweight" before.

    ReplyDelete
  3. @psj
    As an editor, no it's a little heavy. But as an IDE, Emacs is certainly lightweight.

    ReplyDelete
  4. how does this IDE perform compared to other python IDEs?? BTW, I also have a blog and a web directory, would you like to exchange links? let me know on emily.kovacs14@gmail.com

    ReplyDelete
  5. I love emacs too, but let's hope no vim guy is here as they would pick on emacs being "lightweight" ;-)

    ReplyDelete
  6. vim is ok, http://ergoemacs.org/emacs/i/emacs_vi_power_drill_cartoon.png, emacs is better :D

    ReplyDelete