Debug python programs

erick_bodine at attbi.com erick_bodine at attbi.com
Fri Sep 12 17:26:51 CEST 2003


I have found a combination of the logging and optparse modules to be a
very effective alternative to #1 (Both come standard with 2.3 or you
can download/install them yourself).  That way I just hand my script
--debug, sprinkle my code where I want with log.debug("message") and
voila! I get debug messages and the code looks much cleaner.

I can also do the same with whatever modules I create and import by
calling getLogger() at the top of the module
ie. log = logging.getLogger("auto_test") 

import logging
from optparse import OptionParser

p = OptionParser()
p.add_option("", "--debug", action="store_const", const=1, default=0,
            dest="debug", help="Print out debug information")

log = logging.getLogger("auto_test")
handler = logging.StreamHandler()
    
if opts.debug == 1:
    log.setLevel(logging.DEBUG)
    format = logging.Formatter("%(asctime)s %(levelname)-3s
[%(module)s:%" \
                                "(lineno)d] %(message)s")
else:
    log.setLevel(logging.INFO)
    format = logging.Formatter("%(asctime)s %(levelname)-3s
%(message)s")
        
handler.setFormatter(format)
log.addHandler(handler)    

Gotta love the snake!

--ERick


Jeremy Jones <zanesdad at bellsouth.net> wrote in message news:<mailman.1063284197.17837.python-list at python.org>...
> * York (yorklee70 at yahoo.com) wrote:
> > Hi, anybody,
> > 
> > Would you please recommend some good softwares/methods for 
> > tracking/debugging python codes.
> > 
> > Thanks,
> > York
> 
> You've got lots of options.
> 
> 1) Your standard insertion of "print" statements throughout the code.  A
> lot of times, this is good enough to get the job done.  I typically set an
> instance variable named DEBUG for each class that I create (in __init__,
> set self.DEBUG = 0 or 1).  Then I have lots of
> if self.DEBUG:
>     print "whatever" #insert debug statements here
> It's not the most elegant thing, but man, has it come in handy when you
> don't need a full-blown debugger.  (Segue into number 2)
> 
> 2) Python comes with a pretty good debugger built in.  Here are the docs:
> http://www.python.org/doc/current/lib/module-pdb.html
> 
> 3) pychecker.  I know, I know, I know - it's not a debugger.  But if you
> point it at your code, it'll inspect it and can help you uncover some
> mistakes that can bite you in the rear.
> 
> 4)  trace.py.  Never used it, but it's in the standard distribution now
> under Tools/scripts.  (I'm including this line item since you mentioned
> "tracking".  I guess this is what you mean?)
> 
> HTH
> 
> 
> Jeremy Jones




More information about the Python-list mailing list