Using pdb and ipdb Interactive Debuggers in Python
This article introduces Python's interactive debuggers pdb and ipdb, demonstrating how to set breakpoints, step through code, inspect variables, handle exceptions, use conditional breakpoints, and perform remote debugging through concise code examples and command explanations.
In Python, several interactive debuggers such as pdb and ipdb help debug complex issues by allowing line‑by‑line execution, variable inspection, breakpoints, and code navigation.
1. Using the pdb debugger:
import pdb
def divide(x, y):
result = x / y
return result
pdb.set_trace() # set breakpoint
divide(10, 0)2. Common pdb commands:
- n: execute next line
- s: step into function call
- c: continue until next breakpoint
- l: list current source context
- p <variable>: print variable value
- q: quit debugger3. Using the ipdb debugger:
import ipdb
def divide(x, y):
result = x / y
return result
ipdb.set_trace()
divide(10, 0)4. ipdb commands are similar to pdb commands.
5. Tracing code execution flow:
import pdb
def foo():
print("foo")
bar()
def bar():
print("bar")
pdb.set_trace()
foo()6. Viewing variable values:
import pdb
def foo():
x = 10
pdb.set_trace()
y = x + 5
print(y)
foo()7. Jumping to a specific line:
import pdb
def foo():
print("foo")
pdb.set_trace()
print("bar")
foo()8. Setting conditional breakpoints:
import pdb
def foo():
for i in range(10):
pdb.set_trace() # breakpoint
print(i)
foo()9. Entering the debugger on exception:
import pdb
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
pdb.post_mortem() # enter debugger on exception
return result
divide(10, 0)10. Remote debugging:
import pdb
import remote_pdb
def foo():
print("foo")
remote_pdb.set_trace(host='0.0.0.0', port=4444) # start remote debugger
print("bar")
foo()These examples illustrate common usages of pdb and ipdb ; they can be adapted and extended to suit specific debugging needs, improving development efficiency and code quality.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.