dimanche 19 février 2012

debugging notes with python

- with pdb, use aliases

# Ned's .pdbrc
# Print a dictionary, sorted. %1 is the dict, %2 is the prefix for the names.
alias p_ for k in sorted(%1.keys()): print "%s%-15s= %-80.80s" % ("%2",k,repr(%1[k]))
alias pi p_ %1.__dict__ %1. .. # instance variables of %1
alias ps pi self ............. # instance variables of self.
alias pl p_ locals() local: .. # Print the locals.
alias nl n;;l ................ # Next and list.
alias sl s;;l ................ # and step and list.
alias uu u;;u ................ # up the stack
alias dd d;;d ................ # down the stack
source : http://stackoverflow.com/a/1624037
- use sys hooks to react on exception


def traceit(frame, event, arg):
   if event == "line":
        lineno = frame.f_lineno
        print "line", lineno
   return traceit

def main():
print 
"In main" for i in range(5): print i, i*3 print "Done."

sys.settrace(traceit)
main()
source : http://www.dalkescientific.com/writings/diary/archive/2005/04/20/tracing_python_code.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# code snippet, to be included in 'sitecustomize.py'
import sys

def info(type, value, tb):
   if hasattr(sys, 'ps1') or not sys.stderr.isatty():
      # we are in interactive mode or we don't have a tty-like
      # device, so we call the default hook
      sys.__excepthook__(type, value, tb)
   else:
      import traceback, pdb
      # we are NOT in interactive mode, print the exception...
      traceback.print_exception(type, value, tb)
      print
      # ...then start the debugger in post-mortem mode.
      pdb.pm()

sys.excepthook = info
source : http://code.activestate.com/recipes/65287/
- simple logging 
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('This is a debug message.')
source : http://aymanh.com/python-debugging-techniques#logging