Per Erik Strandberg /cv /kurser /blog

I needed to look this up twice in one week so I wrote this little instruction to remind me.See also the official python docs: [1]

The output you are looking for is something with filename, rownumber and method of where the debug method is called. Something like:

[spam.py:42 launch_a_lot] Continue with the spanking.

More or less all we need to do is to use the extract_stack method and take a look at element with index -2 (element with index -1 will be the debug method itself). Something like this:

def debug(msg):    
    caller = extract_stack()[-2]
    print "[%s:%s %s] %s" % ( caller[0], caller[1], caller[2], msg )

A more complete example with Python Doctest And Docstring:

"""
Short example of a debug print in python using the traceback module.
Written by Per Erik Strandberg in 2012. See also the official python docs:
http://docs.python.org/library/traceback.html
"""

from traceback import extract_stack

def debug(msg):
    """
    Prints the debug info with an extract of the traceback. Typical output is
    a line with the filename, rownumber and a message. Something like this:
    [spam.py:42 launch_a_lot] Continue with the spanking.
    
    1 - This first example illustrates that a message can be passed.
        >>> debug( "debug inside the doctest" ) # doctest:+ELLIPSIS
        [...] debug inside the doctest
        
    2 - Typically you will use it inside other methods to get information about
        the values of some parameters. Note that the method name is in there:
        >>> def meal( egg, spam, bacon ):
        ...     debug( "%s %s %s" % ( spam, spam, spam ))
        ...     return egg + spam + bacon
        ...
        >>> _ = meal( 12, 32, 33 ) # doctest:+ELLIPSIS
        [...:2 meal] 32 32 32
        
    3 - Also note that the name of the file is corrupted in this example due to
        some internal doctest issue. 
        >>> debug( "Punch the duck!" )
        [<doctest __main__.debug[3]>:1 <module>] Punch the duck!
    """
    
    caller = extract_stack()[-2]
    print "[%s:%s %s] %s" % ( caller[0], caller[1], caller[2], msg )
    return

# This is included to run the doctests:
if __name__ == '__main__':
    import doctest
    doctest.testmod()    
    debug( "doctests completed" )


This page belongs in Kategori Programmering.