MCS 275 Spring 2022
Emily Dumas
Course bulletins:
Suppose a Python program has a bug.
Wouldn't it be nice if you could run the program slowly, monitoring values of variables along the way?
The built-in Python debugger, called pdb
, makes this possible. Key features:
python -m pdb myprogram.py alpha beta 3
Runs myprogram.py
with command line arguments ["alpha","beta",3]
, but in the debugger.
The program starts in a paused state, and a prompt is shown where we can enter commands (to resume, run a single line, show values of variables, etc.)
Running the program:
Inspecting the situation:
pp
EXPR
-- Evaluate EXPR
and display the result nicely ("pretty print")display
EXPR
-- Every time execution is paused, show the value of EXPR
if it has changed.Rather than single-stepping, it is often helpful to keep running until a certain part of the code is reached.
A place where execution is supposed to stop and return control to the debugger is a breakpoint.
b
FILE:LINE_NUM
-- Set breakpoint by line.b
FUNCTION_NAME
-- Set a breakpoint by function name.cl
-- Clear all breakpoints.If an uncaught exception occurs when a program is running in pdb
, the debugger pauses at the moment of the exception to let you investigate.
This is called a "post mortem" (after death) investigation of the program. You can't continue or step, but you can examine the values of variables, etc.
What if f()
calls g()
, and you are paused inside g
but want to know the value of a local variable of f
?
u
or up
-- Move one step up the traceback, to the function which called this one.d
or down
-- Move one step down the traceback, to the function which called this one.w
or where
-- Show the current traceback.Measuring the amount of time various parts of a program take is called profiling.
Usually you should focus on correctness first, then profile before considering optimization (changing code to make it faster).