python quickie : retrace function steps?

mackstann mack at incise.org
Wed Aug 20 12:55:39 EDT 2003


On Wed, Aug 20, 2003 at 09:20:29AM -0700, 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 came up with this a while back and kinda forgot about it until this
post:

tb = traceback.extract_stack()
print ((len(tb)-2)*"  " + tb[-2][2])

This indents each function call by two spaces, and when functions call
each other, they nest deeper and deeper.  E.g.:

---------------------------

import traceback
 
def debug():
  tb = traceback.extract_stack()
  print ((len(tb)-2)*"  " + tb[-2][2])
           
def f1(): debug(); f2()
def f2(): debug(); print "five plus five is", 5+5
def f3(): debug(); f1()
def f4(): debug(); f3()

if __name__ == "__main__":
  f4()

---------------------------

% python tmp.py 
  f4
    f3
      f1
        f2
five plus five is 10

---------------------------

> i.e. printted output of error would be:
>                   
>             error with function 3
>               function 3 called from function 2
>               function 2 called from function 1
> 
> In perl there is a function called CALLER, which I have used to the
> same effect, i was wondering if python had something similar for this?

If I change the comma in the print statement above to a +, I get:

  File "tmp.py", line 13, in ?
    f4()
  File "tmp.py", line 10, in f4
    def f4(): debug(); f3()
  File "tmp.py", line 9, in f3
    def f3(): debug(); f1()
  File "tmp.py", line 7, in f1
    def f1(): debug(); f2()
  File "tmp.py", line 8, in f2
    def f2(): debug(); print "five plus five is" + 5+5
TypeError: cannot concatenate 'str' and 'int' objects

Do you want something different from that?  If so, different in what way?

-- 
m a c k s t a n n  mack @ incise.org  http://incise.org
Absent, adj.:
	Exposed to the attacks of friends and acquaintances; defamed;
slandered.





More information about the Python-list mailing list