I have talked about Python a number of times in the past, but one thing that I haven't really touched much upon is debugging Python. There are two distinct approaches you might take, depending on whether you're debugging Python code, or whether you're debugging something in a native library. Today I want to talk about the former.
The pdb debugger is the package to use, but the linked reference goes into quite a bit of detail on how to access the debugger package and not so much on using it in practice. So let's start with a hypothetical exception you might run into.
You run a command like python3 blargh.py
and then you get an error of this sort. What to do next?
Traceback (most recent call last):
File "/Users/foo/blargh.py", line 10, in <module>
main()
File "/Users/foo/blargh.py", line 20, in main
raise e
File "/Users/foo/blargh.py", line 30, in foo
l = blargh()
File "/Users/foo/blargh.py", line 40, in blargh
raise ValueError("oh no")
ValueError: oh no
To debug this, you can take the following approach. Note that the commands are shortcuts that resembly gdb/lldb, and you can get help with h
.
python3 -m pdb blargh.py
b blargh
c
p EXPR
to evaluate an expression, n
to step to the next statement, and s
to step inside.bt
will print out the backtrace.x
exits the debugger when you're done.Happy Python debugging!