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:

  1. Run the script in the terminal.

  2. The debugger will stop at pdb.set_trace().

  3. Commands like n (next), c (continue), and q (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 list to view the code around the current line.

  • Use continue to run until the next breakpoint.


4. Inspecting Variables

Inspecting:

  • Use p x or p y to print variable values.

  • Use whatis x to check the type of a variable.


5. Using break Command

Setting Breakpoints:

  • Inside the debugger, type break 2 (line 2 of process_data) to stop the program at that line.


6. Using Conditional Breakpoints

Conditional Breakpoints:

  • Inside the debugger, type break 5, num > 10 to 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 where or bt to view the call stack and see how you reached the current point.


10. Exiting the Debugger

Exit Commands:

  • Use q to quit the debugger.

  • Use c to 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