p1-insta485-static

Python Debugging Tutorial

This tutorial will explain how to use an enhanced Python debugger called PDB++.

Install

Install pdbpp (AKA PDB++). If you set up a virtual environment, you’ll have to install it again in your virtual environment.

$ pip3 install pdbpp

Run

Create a sample file called hello.py to debug. This short program will create a directory.

import os
dirname = "hello/world/"
os.mkdir(dirname)
print("Created {}".format(dirname))

Run it. You’ll get an error.

$ python3 hello.py
Traceback (most recent call last):
  File "hello.py", line 3, in <module>
    os.mkdir(dirname)
FileNotFoundError: [Errno 2] No such file or directory: 'hello/world/'

Add the line import pdb; pdb.set_trace() to your file. New in Python 3.7 breakpoint() is an alternative to import pdb; pdb.set_trace().

import os
dirname = "hello/world/"
import pdb; pdb.set_trace()
os.mkdir(dirname)
print("Created {}".format(dirname))

Run again. The program stops at a breakpoint on the line with import pdb; pdb.set_trace().

$ python3 hello.py
> /Users/awdeorio/hello.py(4)<module>()
-> os.mkdir(dirname)
(Pdb++)

Sticky mode

Try sticky mode. You’ll now see both your code and the pdb console at the same time.

$ python3 hello.py
[0] > /Users/awdeorio/hello.py(4)<module>()
-> os.mkdir(dirname)
(Pdb++) sticky
> /Users/awdeorio/hello.py(4)

   1     import os
   2     dirname = "hello/world/"
   3     import pdb; pdb.set_trace()
   4  -> os.mkdir(dirname)
   5     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.

$ python3 hello.py
[0] > /Users/awdeorio/hello.py(4)<module>()
-> os.mkdir(dirname)
(Pdb++) os.m
          major     makedev   makedirs  minor     mkdir     mkfifo    mknod
(Pdb++) os.m

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 hello.py
[0] > /Users/awdeorio/hello.py(4)<module>()
-> os.mkdir(dirname)
(Pdb++) p dirname
'hello/world/'

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/hello.py(5)<module>()
-> print("Created {}".format(dirname))

Quit.

(Pdb) q
Traceback (most recent call last):
... (ignore the error here)