python quickie : retrace function steps?

Peter Hansen peter at engcorp.com
Wed Aug 20 12:43:36 EDT 2003


Matt Smith wrote:
> 
> If I was to make a function call another function, and from that
> function, call another function (so that now I was in a 3rd function)
> something like this:
> 
> (function 1)
>      |________(function 2)
>                     |________(function 3)
> 
> Is there away I can print out the path my Program had taken (i want to
> do this as part of my error checking, so a user would always know the
> path my program took)?
> 
> i.e. printted output of error would be:
> 
>             error with function 3
>               function 3 called from function 2
>               function 2 called from function 1

This is called a traceback, and Python handles them naturally whenever
an Exception is raised.  In this case, if your own code detects an
error, you would raise a custom exception (subclassed from Exception).
You should be able to find dozens of examples pretty easily.

Also read about the "traceback" module, as it has handy information
about and functions for this stuff.  Also the sys._getframe() function
could be of use.

Try this inside your function3 to see the effect:

  raise Exception('too much spam!)

If you hit that line, your program should exit and Python will print
the full traceback at the console (assuming the program was launched
from the console).

-Peter




More information about the Python-list mailing list