p1-insta485-static
Python Debugging Tutorial
This tutorial will explain how to use an enhanced Python debugger called PDB+.
Install
Install pdbp
(AKA PDB+). If you set up a virtual environment, you’ll have to install it again in your virtual environment.
$ pip3 install pdbp
Pitfall: Avoid using pdbpp
(AKA PDB++) as it is no longer maintained.
Run
Create a sample file called pdbtest.py
to debug. This short program will create a directory.
import os
dirname = "tmp/pdbtest/"
os.mkdir(dirname)
print("Created {}".format(dirname))
Run it. You’ll get an error.
$ python3 pdbtest.py
Traceback (most recent call last):
File "pdbtest.py", line 3, in <module>
os.mkdir(dirname)
FileNotFoundError: [Errno 2] No such file or directory: 'tmp/pdbtest/'
Import pdbp
and add the line breakpoint()
to your file.
import os
import pdbp
dirname = "tmp/pdbtest/"
breakpoint()
os.mkdir(dirname)
print("Created {}".format(dirname))
Pitfall: If you forget import pdbp
, you’ll get the boring default PDB.
Run again. The program stops on the line after the breakpoint.
$ python3 pdbtest.py
[0] > /Users/awdeorio/pdbtest.py(4)
1 import os
2 import pdbp
3 dirname = "tmp/pdbtest/"
4 breakpoint()
5 -> os.mkdir(dirname)
6 print("Created {}".format(dirname))
(Pdb+) q
Traceback (most recent call last):
... (ignore the error here)
Tab completion
Try tab completion. Type os.m
, followed by the TAB key. You may need to press TAB twice.
$ python3 pdbtest.py
[0] > /Users/awdeorio/pdbtest.py(4)
1 import os
2 import pdbp
3 dirname = "tmp/pdbtest/"
4 breakpoint()
5 -> os.mkdir(dirname)
6 print("Created {}".format(dirname))
(Pdb+) os.m
major makedev makedirs minor mkdir mkfifo mknod
We see that there are two very similar ways to create a directory. That’s our bug! We should have used makedirs()
instead of mkdir()
.
PDB commands
We’ll show you a couple of PDB commands. You might also like this pdb
cheat sheet.
Print a variable name.
$ python3 pdbtest.py
[0] > /Users/awdeorio/pdbtest.py(4)
1 import os
2 import pdbp
3 dirname = "tmp/pdbtest/"
4 breakpoint()
5 -> os.mkdir(dirname)
6 print("Created {}".format(dirname))
(Pdb+) p dirname
'tmp/pdbtest/'
Change a value while the program is running.
(Pdb+) dirname = "hello"
(Pdb+) p dirname
'hello'
Execute the next line of code.
(Pdb+) n
[0] > /Users/awdeorio/pdbtest.py(5)
1 import os
2 import pdbp
3 dirname = "tmp/pdbtest/"
4 breakpoint()
5 os.mkdir(dirname)
6 -> print("Created {}".format(dirname))
Quit.
(Pdb+) q
Traceback (most recent call last):
... (ignore the error here)
Pitfall: If you’re running pdbp
with pytest
, you’ll need to use -s
. Review the pytest
tutorial for more details.
Acknowledgments
Original document written by Andrew DeOrio awdeorio@umich.edu.
This document is licensed under a Creative Commons Attribution-NonCommercial 4.0 License. You’re free to copy and share this document, but not to sell it. You may not share source code provided with this document.