2

I've recently discovered the very useful '-i' flag to Python

-i     : inspect interactively after running script, (also PYTHONINSPECT=x)
         and force prompts, even if stdin does not appear to be a terminal

this is great for inspecting objects in the global scope, but what happens if the exception was raised in a function call, and I'd like to inspect the local variables of the function? Naturally, I'm interested in the scope of where the exception was first raised, is there any way to get to it?

saffsd
  • 23,742
  • 18
  • 63
  • 67
  • Check this question: [Starting python debugger automatically on error](http://stackoverflow.com/questions/242485/starting-python-debugger-automatically-on-error) – tzot May 25 '09 at 13:41
  • Thanks but this is not exactly what I am looking for. I'd prefer not to have to wrap the code if possible. – saffsd May 25 '09 at 13:59

3 Answers3

7

At the interactive prompt, immediately type

>>> import pdb
>>> pdb.pm()

pdb.pm() is the "post-mortem" debugger. It will put you at the scope where the exception was raised, and then you can use the usual pdb commands.

I use this all the time. It's part of the standard library (no ipython necessary) and doesn't require editing debugging commands into your source code.

The only trick is to remember to do it right away; if you type any other commands first, you'll lose the scope where the exception occurred.

Vicki Laidler
  • 3,415
  • 1
  • 20
  • 17
  • Interesting. But why does it not let you access the variables like in a regular pdb session? I have to do print varname for the result to show up. – Unknown May 31 '09 at 04:48
5

In ipython, you can inspect variables at the location where your code crashed without having to modify it:

>>> %pdb on
>>> %run my_script.py
Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
4

use ipython: http://mail.scipy.org/pipermail/ipython-user/2007-January/003985.html

Usage example:

from IPython.Debugger import Tracer; debug_here = Tracer()

#... later in your code
debug_here()  # -> will open up the debugger at that point.

"Once the debugger activates, you can use all of its regular commands to step through code, set breakpoints, etc. See the pdb documentation from the Python standard library for usage details."

Brian Gianforcaro
  • 26,564
  • 11
  • 58
  • 77
reto
  • 16,189
  • 7
  • 53
  • 67