Python Debugging w/ breakpoint()
Let’s look at how to debug python programs without an IDE.
Debugging
We use print statements to easily and lazily debug python programs. It is an easy way to figure out what’s worng with your code and where you code actually flows through. If you use an IDE for debugging, they provide debugging tools to make you life easy. But if you need more interactive way of debugging with no IDE support, then you need to know the following command.
Let’s write a simple test code for this purpose. Let’s try to debug the following loop for to see the value of variable a.
a = [1, 2, 3, 4]
for each in a:
print(a)
Now to do this in Python 3.7 or above you can use the
breakpoint()
function. So the code will look as below.
a = [1, 2, 3, 4]
for each in a:
breakpoint()
print(a)
for older Python versions instead of breakpoint(), you need to use
import pdb; pdb.set_trace()
So when you run your script it would stop at the breakpoint. Then you can enter commands in the terminal to continue debugging.
Following are the commands you can use:
Navigating Code (within the Pdb interpreter)
l(ist): list 11 lines surrounding the current line
w(here): display the file and line number of the current line
n(ext): execute the current line
s(tep): step into functions called at the current line
r(eturn): execute until the current function’s return is encountered
Controlling Execution
b [#]: create a breakpoint at line [#]
b: list breakpoints and their indices
c(ontinue): execute until a breakpoint is encountered
clear[#]: clear breakpoint of index [#]
Changing Variables / Interacting with Code
p [var name]: print value of the variable
!<expr>: execute the expression <expr>
**NOTE: this acts just like a python interpreter
run [args]: restart the debugger with sys.argv arguments [args]
q(uit): exit the debugger
source: https://web.stanford.edu/class/physics91si/2013/handouts/Pdb_Commands.pdf