When the Python interpreter encounters an error or exceptional condition while running your code, it quits the program and prints a stack trace. I typically would like to inspect the stack at the point of error to figure out the cause of it. It would be nice to print out some of the local variables you suspect at that point, walk up the stack frames to the calling functions and inspect some of their variables too. All of this is easily possible in Python by using the Python debugger module!
- You can run your script with the
pdbmodule using any one of these commands:
$ pdb my_script.py $ python -m pdb my_script.py $ pdb3 my_script.py $ python3 -m pdb my_script.py
When run explicitly like this, PDB will stop at the first function.
- Alternatively, you can make the Python interpreter to invoke the debugger and stop at a line by adding to the code and running that script:
import pdb; pdb.set_trace()
- Once your program has stopped, you can add more breakpoints, step through the code and inspect variables. For the entire list of commands available at the debugger, see PDB documentation. You will notice that they are similar (but not the same) as GDB commands.
Some of the most common commands are:
bto set breakpoints,
cto continue execution,
wto inspect the stack trace,
dto move up and down the call stack.
To move through code,
sto step into functions,
nto execute the next statement and
returnto return from methods.
To print out variables or values, use the
pcommand. For example:
p foobar p type(foobar)
You can even execute statements that assign to new or existing variables and call methods at the debugger prompt.
If you need tab completion, colorful syntax highlighting and other interactive features, then I recommend using IPDB. It is a drop-in replacement for pdb.
Installing it is easy:
$ sudo apt install python-ipdb $ sudo apt install python3-ipdb
Using it is similar to PDB:
$ ipdb my_script.py $ python -m ipdb my_script.py $ ipdb3 my_script.py $ python3 -m ipdb my_script.py
Tried with: Python 3.5.1 and Ubuntu 16.04