views:

177

answers:

4

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?

+4  A: 

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."

reto
thank you brian!
reto
+3  A: 

Check this question: Starting python debugger automatically on error

ΤΖΩΤΖΙΟΥ
Thanks but this is not exactly what I am looking for. I'd prefer not to have to wrap the code if possible.
saffsd
+4  A: 

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

>>> %pdb on
>>> %run my_script.py
EOL
+3  A: 

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
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