Advertisement
Advanced Python, Debugging & Profiling

How do you use pdb's post-mortem debugging mode to inspect a program's state exactly at the point where an unhandled exception occurred?

Short answer

pdb.post_mortem() (or running a script with `python -m pdb script.py` and letting it crash) drops you into the debugger at the EXACT frame where an exception was raised, letting you inspect local variables and the call stack as they existed at the moment of failure, rather than…

Save Python mock interview
Advertisement
AModel answer
pdb.post_mortem() (or running a script with `python -m pdb script.py` and letting it crash) drops you into the debugger at the EXACT frame where an exception was raised, letting you inspect local variables and the call stack as they existed at the moment of failure, rather than needing to reproduce the bug with a manually-placed breakpoint.
import pdb

try:
    risky_operation()
except Exception:
    pdb.post_mortem()  # drops into the debugger AT the point of failure, with full context
Real-world example
Investigating an unexpected crash's exact state (local variables, call stack) without needing to reproduce it with a manually inserted breakpoint.
Likely follow-ups
  • How does 'python -m pdb -c continue script.py' automate reaching post-mortem debugging for an uncaught exception?
Related topics