saffsd
saffsd

Reputation: 24292

How do I inspect the scope of a function where Python raises an exception?

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?

Upvotes: 2

Views: 1431

Answers (3)

Vicki Laidler
Vicki Laidler

Reputation: 3489

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.

Upvotes: 7

Eric O. Lebigot
Eric O. Lebigot

Reputation: 94475

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

>>> %pdb on
>>> %run my_script.py

Upvotes: 5

reto
reto

Reputation: 16732

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

Upvotes: 4

Related Questions