Neat trick: invoking a Python debugger at an arbitrary point in your program

Do you find yourself occasionally wishing you could freeze a misbehaving program at an arbitrary point in time and then examining what was going on interactively?

That's exactly what the debugger is for, but sometimes it's just too much of a bother to run your program inside it, you have to set breakpoints, etc.

Well there's a really simple alternative: call the debugger from an arbitrary point in your program, like this...

import pdb; pdb.set_trace();

You can then examine the state of your program (e.g., locals, globals).

Note that many complex programs take advantage of Python's interpreted nature and go one step further by actually providing the user a way to hook into an interactive, interpreted Python environment on-demand (e.g., debugging console listening on a given port). This allows you to explore your program, usually a long living framework or daemon, from the inside while it is running.

Twisted does this, for example.


Liraz Siri's picture

I just experimented with set_trace() and I have to admit I like it better than"pass", globals(), locals()). Thanks Reid!
Liraz Siri's picture

Thanks for recommending pdbpp. It rocks. I installed it on my TurnKey-based system as follows::
apt-get install python-setuptools
easy_install pdbpp
Besides the color syntax highlighting, I especially like the new sticky command.


Add new comment