The Python Debugger Step-through Debugging with pdb
suggest changeThe Python Standard Library includes an interactive debugging library called pdb. pdb has extensive capabilities, the most commonly used being the ability to ‘step-through’ a program.
To immediately enter into step-through debugging use:
python -m pdb <my_file.py>
This will start the debugger at the first line of the program.
Usually you will want to target a specific section of the code for debugging. To do this we import the pdb library and use set_trace() to interrupt the flow of this troubled example code.
Running this program will launch the interactive debugger. The divide function in that transcript is not shown on this page.
python foo.py
> ~/scratch/foo.py(5)divide()
-> return a/b
(Pdb)
Often this command is used on one line so it can be commented out with a single # character.
import pdb; pdb.set_trace()
At the (Pdb) prompt commands can be entered. These commands can be debugger commands or Python. To print variables we can use p from the debugger, or Python’s print.
(Pdb) p a
1
(Pdb) print(a)
1
To see a list of all local variables, call the built-in function locals().
These are good debugger commands to know:
b <n> | <f>: set breakpoint at line *n* or function named *f*.
# b 3
# b divide
b: show all breakpoints.
c: continue until the next breakpoint.
s: step through this line (will enter a function).
n: step over this line (jumps over a function).
r: continue until the current function returns.
l: list a window of code around this line.
p <var>: print variable named *var*.
# p x
q: quit debugger.
bt: print the traceback of the current execution call stack
up: move your scope up the function call stack to the caller of the current function
down: Move your scope back down the function call stack one level
step: Run the program until the next line of execution in the program, then return control back to the debugger
next: run the program until the next line of execution in the current function, then return control back to the debugger
return: run the program until the current function returns, then return control back to the debugger
continue: continue running the program until the next breakpoint (or set_trace is called again)
The debugger can also evaluate Python interactively. The example is not on this page.
Note:
If any of your variable names coincide with the debugger commands, use an exclamation mark ‘!’ before the var to explicitly refer to the variable and not the debugger command. For example, often it might so happen that you use the variable name ‘c’ for a counter, and you might want to print it while in the debugger. A simple ‘c’ command would continue execution till the next breakpoint. Instead use ‘!c’ to print the value of the variable as follows:
(Pdb) !c
4