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
Copy
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
Copy
Command Line Debugging:
Run the script, and you'll enter the debugger for the
multiply_numbers(4, 5)function.
3. Using Breakpoints
Copy
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
Copy
Inspecting:
Use
p xorp yto print variable values.Use
whatis xto check the type of a variable.
5. Using break Command
Copy
Setting Breakpoints:
Inside the debugger, type
break 2(line 2 ofprocess_data) to stop the program at that line.
6. Using Conditional Breakpoints
Copy
Conditional Breakpoints:
Inside the debugger, type
break 5, num > 10to stop only when the condition is true.
7. Stepping Through Code
Copy
Commands:
n: Execute the next line without diving into functions.s: Step into a function call.
8. Post-Mortem Debugging
Copy
Post-Mortem Debugging:
The debugger starts after an exception, allowing you to inspect the code state where the error occurred.
9. Printing Call Stack
Copy
Command:
Use
whereorbtto view the call stack and see how you reached the current point.
10. Exiting the Debugger
Copy
Exit Commands:
Use
qto quit the debugger.Use
cto continue execution until the end of the program.
Last updated