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!
- After you see a Python script fail, just run it again but using 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
- If you do not want to run the PDB module like this, you can also add a hard breakpoint at a line in your code by adding this before that line:
import pdb; pdb.set_trace()
- When run explicitly, PDB will stop at the first function. This is a good point to set breakpoints using the
cto continue execution. It will run the script and should fail at the place where it had failed earlier.
wto inspect the stack trace. Your current frame will be indicated by an arrow. To move up and down the stack, use
- To print out the values of variables in the current stack frame, use the
pcommand, type their name and press Enter.
- For the entire list of commands available at the debugger, see PDB documentation.
- If you need tab completion, colorful syntax highlighting and other interactive features, then install the IPDB module which builds upon IPython to offer these features. Using that 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