When working with Python, it’s not uncommon to encounter bugs or unexpected behavior in your code. In such cases, a powerful tool to aid in debugging is the Python Debugger, commonly known as pdb
. pdb
allows you to interactively debug your Python code, stepping through it line by line, inspecting variables, and executing commands.
Here is a list of some commonly used pdb
commands that can help you diagnose and resolve issues in your code:
Starting the Debugger
python -m pdb script.py
: Start the debugger and run the scriptscript.py
.import pdb; pdb.set_trace()
: Insert this line at the desired point in your code to start the debugger when executing that line.
Controlling Execution
c
: Continue execution until the next breakpoint or until program termination.n
: Execute the next line of code.s
: Step into a function call.r
: Continue execution until the current function returns.
Breakpoints
b
: Set a breakpoint at the current line or specified line number.b function_name
: Set a breakpoint at the start of the specified function.b filename:lineno
: Set a breakpoint at the specified line in the specified file.disable
: Disable a breakpoint.enable
: Enable a disabled breakpoint.
Inspecting Variables
p variable_name
: Print the value of the specified variable.pp variable_name
: Pretty print the value of the specified variable.whatis variable_name
: Print the type of the specified variable.args
: Print the arguments passed to the current function.locals()
: Print all local variables in the current scope.
Stepping
l
: List the current code context (around the current line).ll
: List the entire current function.u
ord
: Move up or down the call stack.q
: Quit the debugger and program execution.
Miscellaneous
help
: Display a list of availablepdb
commands.h command
: Get help on a specific command.!
: Execute an arbitrary Python expression.
These are just a few of the many pdb
commands available for debugging your Python code. Experimenting with these commands will help you uncover issues, understand the flow of your program, and ultimately write more robust code.
Remember, when encountering errors or unexpected behavior, don’t panic. Instead, rely on pdb
and its arsenal of commands to guide you through the debugging process and resolve issues efficiently.