PyTexas 2010 - Debugging in Python
A Hands On Exercise in Python Debugging
Before we even begin, here's how look it up for yourself:
Useful Resources
http://docs.python.org/library/pdb.html - the official pdb documentation
http://openp2p.com/pub/a/python/2005/09/01/debugger.html - lengthy O'Reilly article
http://pythonconquerstheuniverse.wordpress.com/category/the-python-debugger/ - concise blog entry about the basics
http://aymanh.com/python-debugging-techniques - broad debugging blog entry
SECRET - the long form of this presentation/tutorial! I'll provide URL at the end.
In-Talk Code
mean.py
def mean(first, second):
result = first + second / 2
return result
shouldbe = 6
m = mean(4, 8)
print("mean(4,8) =", m)
print("should be:", shouldbe)
print("correct?", m==shouldbe)
sequence.py
print(1)
print(2)
print(3)
import pdb; pdb.set_trace()
print(4)
print(5)
print(6)
print(7)
nested.py
def top():
a = 12
b = 3
print("Hello")
middle()
print("done!")
def middle():
a = 0
c = 9
print("world")
bottom()
def bottom():
d = 88
print("!")
top()
divide (for mean.py)
def divide(x, y):
a = 3 / x
b = 4 / y
return a + b
callself.py
import logging
def callself(a=0):
logging.debug(a)
a = a + 1
print(a)
if a < 10:
callself(a)
Outline
How are you debugging?
Staring at it?
Print?
watch out for Python 3
Interactive Console (if you didn't know...)
A better way: pdb
Get some code to debug
pdb reference online, and other good articles
Get into pdb session the easiest way: pdb.set_trace()
how it works and what we can do
interactive help with h(elp)
leaving with q(uit)
repeating with blank lines
Examine the environment
show location with l(ist)
see args with a(rgs)
see return value with retval
look at stack with w(here)
execute statements with ! or p(rint)
Move around
go forward with s(tep), n(ext)
fast-forward with r(eturn), c(ontinue), and unt(il)
go back with j(ump)
The stack
printing the stack with w(here)... and what it means
navigating the stack with u(p) and d(own)
Other ways into pdb
multiple 'set_trace'
after a crash: post-mortem with 'pm' and 'post_mortem'
interactive
as exception handling
without error or source changes: 'run', 'runeval', and 'runcall'
starting pdb without source changes
setting breakpoints with 'break' and 'tbreak'
managing breakpoints with 'clear', 'disable', 'enable'
skipping breakpoints with 'condition' and 'ignore'
hooking into breakpoints with 'commands'
restarting with 'run'
Logging, briefly