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!
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.
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:
b to set breakpoints,
c to continue execution,
w to inspect the stack trace,
d to move up and down the call stack.
To move through code,
s to step into functions,
n to execute the next statement and
return to return from methods.
To print out variables or values, use the
p command. 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