100. pdb Debugging
Here are examples and explanations of how to use Python's built-in pdb debugger for step-by-step debugging:
1. Starting the Debugger
import pdb
def add_numbers(a, b):
pdb.set_trace() # Start debugger here
result = a + b
return result
add_numbers(5, 10)How to Debug:
Run the script in the terminal.
The debugger will stop at
pdb.set_trace().Commands like
n(next),c(continue), andq(quit) help navigate.
2. Debugging from the Command Line
def multiply_numbers(a, b):
result = a * b
return result
if __name__ == "__main__":
import pdb
pdb.run('multiply_numbers(4, 5)')Command Line Debugging:
Run the script, and you'll enter the debugger for the
multiply_numbers(4, 5)function.
3. Using Breakpoints
Key Commands:
Use
break <line_number>to set a breakpoint.Use
listto view the code around the current line.Use
continueto run until the next breakpoint.
4. Inspecting Variables
Inspecting:
Use
p xorp yto print variable values.Use
whatis xto check the type of a variable.
5. Using break Command
Setting Breakpoints:
Inside the debugger, type
break 2(line 2 ofprocess_data) to stop the program at that line.
6. Using Conditional Breakpoints
Conditional Breakpoints:
Inside the debugger, type
break 5, num > 10to stop only when the condition is true.
7. Stepping Through Code
Commands:
n: Execute the next line without diving into functions.s: Step into a function call.
8. Post-Mortem Debugging
Post-Mortem Debugging:
The debugger starts after an exception, allowing you to inspect the code state where the error occurred.
9. Printing Call Stack
Command:
Use
whereorbtto view the call stack and see how you reached the current point.
10. Exiting the Debugger
Exit Commands:
Use
qto quit the debugger.Use
cto continue execution until the end of the program.
These examples showcase how to leverage pdb for precise and interactive debugging in Python programs.
Last updated