How to Run the Python Debugger
TechnologyAre you having trouble getting your python code to run? Luckily, there are a couple of ways to figure out what is causing the errors.
The first is to put print statements near where you think things are going wrong. If the print statement executes you know things were working fine until that point. Add more and move them around until you get to the misbehaving line of code.
Yes, I have too many years of experience doing exactly that painful process. One day though I saw another way.
The Python Debugger
Enter the Python Debugger. Running the debugger is pretty simple. Import the pdb module. Call the pdb.set_trace() function. Run your program.
Want to stop? Enter ‘q’ at the Pdb prompt.
Below is a simple program to demonstrate.
import pdb
pdb.set_trace()
x = 1.5
print(x)
y = 2.7
print(x, y)
print(x*y)
print(x+y)
When you run a program pdb evaluates the code step-by-step then prints the code and returns resulting values, if any. In Emacs the line being evaluated is indicated with ‘=>’ on the left side in the source file. When all the steps have been evaluated the debugger returns back to the repl.
In order to evaluate the next step enter ’n’ for ’next’ at the prompt. Running the above code looks like the following on my system.
Debugger evaluating source:
>>>
> /home/eric/src/py-debug.py(4)<module>()
-> x = 1.5
(Pdb) n
> /home/eric/src/py-debug.py(6)<module>()
-> print(x)
(Pdb)
Source being evaluated:
import pdb
pdb.set_trace()
x = 1.5
=>rint(x)
y = 2.7
print(x, y)
print(x*y)
print(x+y)
Notice the ’n’ entered at the (pdb) prompt to move to the next line. The ‘=>’ is on the left side of the current line.
Below is an example evaluating the source code at the command line.
bash $ --> python py-debug.py
> /home/eric/src/py-debug.py(4)<module>()
-> x = 1.5
(Pdb) n
> /home/eric/src/py-debug.py(6)<module>()
-> print(x)
(Pdb) n
1.5
> /home/eric/src/py-debug.py(8)<module>()
-> y = 2.7
(Pdb) n
> /home/eric/src/py-debug.py(10)<module>()
-> print(x, y)
(Pdb) n
1.5 2.7
> /home/eric/src/py-debug.py(12)<module>()
-> print(x*y)
(Pdb) n
4.050000000000001
> /home/eric/src/py-debug.py(14)<module>()
-> print(x+y)
(Pdb) n
4.2
Pretty simple!
At the same time the pdb module is very powerful. Imagine how many print statements even a simple program might need. Let alone a few thousand lines.
We only looked at running the python debugger using a simple example and one basic command. Take a look at the other commands to supercharge your debugging. You might not need so many print() in your code.
Share with Friends!