Sub topic 2
Starting a script under python -m pdb
This chapter assumes you can run Python scripts from a terminal, read a traceback, and have seen the (Pdb) prompt that breakpoint() opens. It covers the second way to start pdb: handing it the whole program from the command line, with no edits to the source.
Why start from the command line
breakpoint() stops the program where you wrote the call. That works when you know where to look and can edit the file. Sometimes you can't do either. You may not know where the bug is, the file may belong to someone else, or you may not want a stray breakpoint() in the code.
Running python -m pdb solves this. The -m flag tells Python to run a module as a program, and here that module is pdb. Pdb loads your script, stops before the first line, and gives you a prompt. From there you set breakpoints, run to them, and step.
python -m pdb script.pyPdb runs your script as __main__, so an if __name__ == "__main__": block runs normally. It also puts the script's directory first on sys.path, so imports of sibling files behave as they do without the debugger.
A worked example
Save this file as stats.py:
import sys
def parse(text):
numbers = []
for item in text.split(","):
numbers.append(int(item))
return numbers
def mean(values):
return sum(values) / len(values)
if __name__ == "__main__":
nums = parse(sys.argv[1])
print(mean(nums))Start it under pdb and give it a bad input. Everything after the script name is passed to the script, so sys.argv[1] will be 1,2,x:
python -m pdb stats.py 1,2,xPdb stops before running anything:
> /home/user/stats.py(1)<module>()
-> import sys
(Pdb)The > line gives the file, the line number in parentheses, and the current function. <module> means top-level code. The -> line is the next statement to run. It has not executed yet.
Type c (continue) to run until something stops the program. Here the int("x") call raises ValueError:
(Pdb) c
Traceback (most recent call last):
...
File "/home/user/stats.py", line 7, in parse
numbers.append(int(item))
ValueError: invalid literal for int() with base 10: 'x'
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> /home/user/stats.py(7)parse()
-> numbers.append(int(item))
(Pdb) p item
'x'
(Pdb) p numbers
[1, 2]
(Pdb) a
text = '1,2,x'You are now inside the frame where the exception was raised, with its variables intact. The a command (short for args) prints the arguments of the current function. The traceback told you what failed, and the prompt lets you see what the data looked like when it failed.
This crash handling is the main advantage of python -m pdb. If the script raises an exception that nothing catches, pdb enters post-mortem mode on its own, and you don't have to wrap anything in try/except. Chapter 11 covers post-mortem debugging in more depth.
Setting breakpoints before the program runs
Because pdb stops at the start, you can place breakpoints first and then run to them:
(Pdb) b parse
Breakpoint 1 at /home/user/stats.py:5
(Pdb) c
> /home/user/stats.py(5)parse()
-> numbers = []
(Pdb) a
text = '1,2,x'
(Pdb) n
> /home/user/stats.py(6)parse()
-> for item in text.split(","):b parse puts a breakpoint on the first executable line of the function parse. You can also write b 12 for a line in the current file, or b other.py:30 for a line in another file. The next chapters cover managing breakpoints in detail. The point here is the order of events. You choose where to stop before any of your code has run.
Skipping the prompt work with -c
Typing the same setup commands on every run gets tedious. The -c option runs a pdb command at startup as if you had typed it. You can repeat it:
python -m pdb -c "b parse" -c "continue" stats.py 1,2,xThis sets the breakpoint, continues, and gives you the prompt already stopped inside parse. Options for pdb go before the script name. Everything after the script name belongs to your script, so a -c placed after stats.py would be passed to stats.py instead of pdb.
For setup you want every time, a .pdbrc file is a better home than -c. That is the subject of a later chapter.
Debugging a module or package
If you normally start your program with python -m mypackage, add -m after the pdb options:
python -m pdb -m mypackage arg1 arg2This runs the package's __main__ module under the debugger, with relative imports working as usual. The -m form of pdb needs Python 3.7 or later.
What happens when the program ends
Pdb does not exit when your script finishes. If the script ends normally you will see:
The program finished and will be restartedThe prompt stays open. Typing c or s runs the script again with the same arguments. Breakpoints you set stay in place. This is useful because you can step through, find that you stopped one line too late, and start over without retyping anything.
The restart command does the same on demand. You can also give it new arguments, as in restart 1,2,3.
To leave, type q (quit). This ends the program immediately, without running remaining code such as finally blocks or exit handlers you might expect.
Restarting runs the script from scratch in a fresh __main__ namespace, but modules the script already imported stay cached in sys.modules. If you edit a helper module and restart, the old version of it may still be in use. When code changes matter, quit and launch pdb again.
Choosing between breakpoint() and python -m pdb
| Question | `breakpoint()` | `python -m pdb script.py` |
|---|---|---|
| Needs a source edit | Yes | No |
| Where it first stops | At the call | Before the first line |
| Stops on an uncaught exception | No | Yes, in post-mortem mode |
| Can be switched off without edits | Yes, with `PYTHONBREAKPOINT=0` | Not applicable, since you chose to run it this way |
| Good for | A known spot in a long run | An unknown crash site, or code you can't edit |
| Cost for a long startup | Run is at full speed until the call | Pdb traces the code, so it runs slower |
The last row matters. Under python -m pdb, the interpreter's tracing hook is active. Code runs noticeably slower than normal while you are inside the debugger's control, and it stays at normal speed only while c is running with no breakpoints that matter. For a program that does heavy computation before the interesting part, a breakpoint() placed near the problem is often the faster route.
Common problems
- Options in the wrong place.
python -m pdb stats.py -c continuesends-c continueto your script. Put pdb options before the script name. - Scripts that read standard input. Pdb reads its commands from standard input too. If your program calls
input()or readssys.stdin, the two compete for the same stream. Redirecting a file into the program (< data.txt) feeds your data to pdb as commands. Have the script read from a file path argument while you debug. - Quitting too early.
qdoes not run cleanup code. If a bug involves afinallyblock oratexithandler, let the program finish withcinstead. - Forgetting the stop is before line 1. The first prompt has run nothing. Variables you expect, such as imports, do not exist yet. Use
nor set a breakpoint and continue. - Debugging with the wrong interpreter.
python -m pdbuses whicheverpythonis first on your path. In a virtual environment, activate it first, or call its interpreter explicitly, so the script sees the right packages.
Exercise
You run python -m pdb tool.py --verbose data.csv. Which program receives --verbose, and what would change if you wrote python -m pdb --verbose tool.py data.csv instead?
Show answer
In the first command, --verbose comes after the script name, so tool.py receives it in sys.argv. In the second, --verbose comes before the script name, so pdb would try to interpret it as one of its own options and fail, because pdb has no such option. Options before the script name belong to pdb. Everything after belongs to the script.
Exercise
Using stats.py from this chapter, write one command line that starts the script with the argument 4,5,6, sets a breakpoint on the function mean, and continues so the prompt appears stopped inside mean. Then say what a would print there.
Show answer
python -m pdb -c "b mean" -c continue stats.py 4,5,6. The breakpoint stops on the first executable line of mean, and a prints values = [4, 5, 6].