Python Debugger (pdb)
Basic Usage of pdb
Python's built-in debugger allows interactive debugging directly in the console:
import pdb
def problematic_function(x, y):
pdb.set_trace() ## Debugging breakpoint
result = x / y
return result
try:
problematic_function(10, 0)
except Exception as e:
print(f"Error: {e}")
pdb Commands
| Command |
Description |
| n (next) |
Execute next line |
| s (step) |
Step into function |
| c (continue) |
Continue execution |
| p (print) |
Print variable value |
| l (list) |
Show current code context |
Logging Module
Configuring Logging
import logging
## Basic logging configuration
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s: %(message)s'
)
def complex_calculation(x, y):
logging.info(f"Inputs: x={x}, y={y}")
try:
result = x / y
logging.debug(f"Calculation result: {result}")
return result
except ZeroDivisionError:
logging.error("Division by zero attempted")
Interactive Debugging Workflow
graph TD
A[Write Code] --> B[Add Breakpoints]
B --> C[Start Debugging]
C --> D{Error Detected?}
D -->|Yes| E[Inspect Variables]
E --> F[Analyze Code]
F --> G[Fix Issue]
D -->|No| H[Continue Execution]
IPython Enhanced Console
Advanced Debugging Features
- Tab completion
- Magic commands
- Interactive object inspection
## IPython magic commands
%debug ## Enter post-mortem debugging
%timeit ## Measure execution time
%run script.py ## Run Python scripts
Remote Debugging Techniques
Using Remote pdb
import rpdb
def remote_debug_function():
rpdb.set_trace() ## Allow remote debugging
## Complex code here
LabEx Debugging Tips
At LabEx, we recommend:
- Always use meaningful logging
- Combine multiple debugging techniques
- Practice debugging with real-world scenarios