Sub topic 11
Debugging after a crash with post-mortem mode
Breakpoints work when you know where to look. After a crash you often don't. Post-mortem debugging lets you open pdb on the exception that already happened. The stack frames from the failure are still in memory, so you can inspect the variables as they were at the moment of failure.
This chapter assumes you can read a traceback, use try/except, run scripts from a terminal, and use the basic (Pdb) commands (p, pp, l, w, u, d, c) from earlier chapters.
What post-mortem mode is
A traceback is a list of the calls that were active when an exception was raised. Python keeps a reference to each of those frames, and each frame holds its local variables. Post-mortem debugging gives pdb that traceback and starts at the innermost frame, where the exception was raised.
The key difference from a normal session is that you cannot resume the program. The code that failed has already unwound. You can read state and move between frames, and you can evaluate expressions. You cannot step forward to see what happens next.
Entry point 1: `pdb.post_mortem()` inside `except`
Call pdb.post_mortem() while an exception is being handled. With no argument it uses that current exception.
import pdb
def main():
data = {"a": 1}
return data["b"]
try:
main()
except Exception:
pdb.post_mortem()When the KeyError is raised, control passes to the except block, and pdb opens on the frame of main(). Type p data to see {'a': 1}, and w to see the stack.
You can also pass a traceback object explicitly: pdb.post_mortem(exc.__traceback__). That is useful when you saved the exception earlier and want to debug it later.
import pdb
errors = []
for raw in ["10", "x", "30"]:
try:
int(raw)
except ValueError as exc:
errors.append(exc)
for exc in errors:
pdb.post_mortem(exc.__traceback__)Here the loop finishes before the debugger starts, so you can look at every failure at once instead of stopping in the middle of a run.
Entry point 2: `python -m pdb script.py`
When you run a script under pdb, an uncaught exception puts you into post-mortem mode without any code changes. Consider this script, saved as prices.py:
def parse_price(raw):
return float(raw.strip("$"))
def total(rows):
result = 0.0
for row in rows:
result += parse_price(row["price"])
return result
rows = [{"price": "$3.50"}, {"price": "$4.25"}, {"price": "n/a"}]
print(total(rows))Run python -m pdb prices.py. Pdb stops at the first line, so type c to continue. After the traceback, the session looks like this:
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> prices.py(2)parse_price()
-> return float(raw.strip("$"))
(Pdb) p raw
'n/a'
(Pdb) u
> prices.py(8)total()
-> result += parse_price(row["price"])
(Pdb) p result
7.75
(Pdb) p row
{'price': 'n/a'}
(Pdb) d
> prices.py(2)parse_price()
-> return float(raw.strip("$"))The failing call received 'n/a'. The loop had already added two prices, and result is 7.75. The bug is in the data, not in parse_price, so the fix belongs in the input handling.
The message "Running 'cont' or 'step' will restart the program" matters. In this mode, c and s restart the script from the beginning, with a fresh process state. They do not continue from the crash. If you want to keep looking at the crashed state, don't type them.
Entry point 3: `pdb.pm()` after the fact
The function pdb.pm() debugs the last unhandled exception of an interactive session. Python's interactive prompt stores that exception in sys.last_exc (3.12 and later) and in sys.last_traceback. Use it when you ran a script with -i, which leaves you at the >>> prompt after the crash:
python -i prices.pyimport pdb
pdb.pm()This only works if an unhandled exception has occurred in that interpreter. In a normal script, sys.last_traceback is never set, and pdb.pm() fails with an AttributeError. This is why pdb.post_mortem() and python -m pdb are the usual choices.
Comparing the entry points
| Entry point | Needs code change | Works on | Typical use |
|---|---|---|---|
| `pdb.post_mortem()` in `except` | Yes | Any exception you catch | Crashes you can reproduce, handled errors you want to examine |
| `python -m pdb script.py` | No | Uncaught exceptions | Quick look at why a script died |
| `python -i script.py` then `pdb.pm()` | No | Last uncaught exception | Looking at a crash after you have seen the traceback |
| `pytest --pdb` | No | Test failures | Failing tests (see the pytest chapter) |
Opening pdb on every crash with `sys.excepthook`
Python calls sys.excepthook for any uncaught exception. You can replace it so that every crash opens a post-mortem session, but only when a human is at the terminal.
import pdb
import sys
import traceback
def debug_hook(exc_type, exc, tb):
if not sys.stdin.isatty() or not sys.stderr.isatty():
sys.__excepthook__(exc_type, exc, tb)
return
traceback.print_exception(exc_type, exc, tb)
pdb.post_mortem(tb)
sys.excepthook = debug_hook
def divide(a, b):
return a / b
print(divide(1, 0))The isatty() check is not decoration. Without it, a cron job or a CI run that crashes would block forever, waiting for input at a prompt nobody will see. Fall back to the default hook outside an interactive terminal.
What you can and cannot do
Post-mortem sessions are for reading. These commands are the most useful:
wshows the full stack, with>marking the frame you are in.uanddmove toward the caller and toward the failure.p,pp,aprint expressions, pretty-print them, and show the arguments of the current function.landllshow the source around the current line, or the whole function.interactopens a Python prompt with the frame's variables, if you want to try several expressions at once.
Commands that try to run code forward, such as n, s, r, and until, don't work in a useful way, and c restarts the program in the python -m pdb case. You can assign variables, but changes affect only the saved frame. They do not fix the program.
Common problems
- The variable you want is gone. After
except ValueError as e:finishes, Python deletese. If you callpdb.post_mortem()after the block ends, use the traceback you saved, not the name. pdb.post_mortem()complains there is no exception. Without an argument it needs an exception being handled right now. Calling it outside anexceptblock raises an error. Pass a traceback, or move the call inside the block.- The state is not what you expected. Locals show the values at the time of the crash, but mutable objects such as lists and dicts may have been changed by code that ran after the exception was raised, for example in
finallyblocks and__exit__methods. Check them against the traceback. - Output differs on the second run. Restarting after
corsre-runs the script. If it reads random numbers, the clock, or a changing file, the crash may not recur. - Memory stays in use. A saved traceback keeps every frame, and every local in them, alive. Drop references (
errors.clear()) when you are done.
Putting it into practice
Post-mortem mode fits the first step of a hypothesis-driven workflow. Read the traceback and form a guess, then use the saved frames to test it. If the guess is "the input was malformed", look at raw and row. If it is "an earlier step produced a bad value", move up with u and check that frame's locals. Once you know the state that led to the failure, you can set a breakpoint() earlier in the code and run again to watch how that state arises.
Exercise
A script crashes with an uncaught exception. You ran it as python -m pdb script.py, typed c, and landed at the post-mortem prompt. You want to look at the state again after trying some commands, so you type c to "continue". What happens, and what should you do instead?
Show answer
Pdb restarts the script from the beginning, because the crashed program cannot be resumed, and the post-mortem state is lost until it crashes again. Instead, use w, u, d, p, pp, l, and interact to inspect the saved frames, and type q when you are done.
Exercise
Why does the sys.excepthook example check sys.stdin.isatty() before calling pdb.post_mortem(), and what does it do when the check fails?
Show answer
When a crash happens in a non-interactive context such as cron or CI, no one can type at the prompt, so pdb would wait forever. The hook then calls the original sys.__excepthook__, which prints the traceback and lets the process exit normally.
Exercise
You collect exceptions in a list during a loop and want to debug the second one after the loop ends. Write the call.
Show answer
pdb.post_mortem(errors[1].__traceback__). Passing the traceback explicitly works outside an except block, because the exception object keeps its traceback.