pdb — The Python Debugger

docs

The module pdb defines an interactive source code debugger for Python programs. It supports setting (conditional) breakpoints and single stepping at the source line level, inspection of stack frames, source code listing, and evaluation of arbitrary Python code in the context of any stack frame. It also supports post-mortem debugging and can be called under program control.

The typical usage to break into the debugger is to insert:

import pdb; pdb.set_trace() or: breakpoint() at the location you want to break into the debugger, and then run the program.

breakpoint(*args, **kws)

This function drops you into the debugger at the call site.

Debugger Commands

h(elp) [command]

Without argument, print the list of available commands.

w(here) [count]

Print a stack trace, with the most recent frame at the bottom.

s(tep)

n(ext)

l(ist) [first[, last]]

display [expression]

.pdbrc file

If a file .pdbrc exists in the user’s home directory or in the current directory, it is read with ‘utf-8’ encoding and executed as if it had been typed at the debugger prompt, with the exception that empty lines and lines starting with # are ignored. This is particularly useful for aliases. If both files exist, the one in the home directory is read first and aliases defined there can be overridden by the local file.

# .pdbrc example for pdb (Python Debugger)

# Print a message when pdb starts
!echo "Welcome to pdb!"

# Define a user command to print the current stack trace
alias st for i in range(0, len(curframe.f_back.f_back)): print(curframe.f_back.f_back)
# Set an initial breakpoint at main.py:10
b main.py:10

# Define a convenient user command to display variables
alias pv p locals(); p globals()

# Step into code automatically after start
s
# .pdbrc configuration file for pdb

# Set favorite breakpoints
break mymodule.py:45
break myutils.py:30

# Automatically step into the next line
command break mymodule.py:45
  n
  p some_variable
end

# Define a macro to show context about an object
def showctx obj
  p getattr(obj, "name", None)
  p getattr(obj, "status", None)
end

# Print the current stack on entry
where

# List the last 15 lines when hitting a breakpoint
command
  list 15
end

# Useful aliases
alias r return
alias c continue
alias l list

# Set ignore rules (ignore breakpoints after first hit)
ignore 1 1