[Freeipa-devel] Python debugging tip

John Dennis jdennis at redhat.com
Tue Jun 12 18:39:23 UTC 2012


Every so often I'm confronted with being unable to determine where an 
exception is being raised. Unfortunately pdb (Python debugger) cannot be 
set to break on an exception (oddly missing functionality).

It turns out that pdb is built upon a simple Python API, a callback that 
is invoked whenever the interpreter "steps". The callback is set with 
sys.settrace() (see Python doc for full explanation).

To find my elusive exception I simply added this tiny bit of code that 
sets the tracing function and whenever a TypeError occurred it printed 
out the stacktrace.

Caveat, it's verbose, will print out every TypeError exception including 
those you're not looking for and it will do so for every place on the 
stack. A somewhat minor inconvenience if you can't find the exception 
using any of the other means.  You can of course tweak this to be much 
more specific by examining the other context information passed to the 
callback but for a quick dirty hack it didn't seem worthwhile.

Hope its useful to someone.

John


import sys
import traceback

def tracefunc(frame, event, arg):
     if event == 'exception':
         exc, value, tb = arg
         if isinstance(value, TypeError):
             print ">>> Exception %s" % value
             print ''.join(traceback.format_tb(tb))
     return tracefunc

sys.settrace(tracefunc)


-- 
John Dennis <jdennis at redhat.com>

Looking to carve out IT costs?
www.redhat.com/carveoutcosts/




More information about the Freeipa-devel mailing list