Your routine may want to know who called it. fmWhence() will print the calling sequence up to the number of levels specified.
This version will print its results; modify to get your desired behavior.
- -- Larry Bugbee
code
1 """
2 fmWhence.py
3
4 Sometimes you get to a routine, but want to know who called
5 you. This routine will print the calling sequence up to the
6 number of levels specified. Default is 1. Season to taste.
7
8 Larry Bugbee
9 May 2001
10
11 v2: 6-1 re-wrote to return list and optional print
12 """
13
14 # ------------------------------------------------------------------------------
15
16 import traceback, os
17
18 def fmWhence(levels=1, see=0):
19 """ This routine will print the calling sequence up to the
20 number of levels specified. Default is 1.
21 """
22 try:
23 raise Exception, 'dummy' # need an exception
24 except:
25 stack = traceback.extract_stack() # get list of frames
26 ls = len(stack) # for convenience
27 levels = min(levels, ls-2) # user asks too much?
28 at = stack[-2][2] # where are we at?
29 print '\nfrom whence I came:'
30 # we want process the stack from the bottom up, hence the -1.
31 # we also want to ignore the two at the very bottom, hence the ls-3
32 for i in range(ls-3, ls-3-levels, -1):
33 file = os.path.basename(stack[i][0]) # just want the file name
34 line = stack[i][1] # extract line number
35 name = stack[i][2] # name of calling routine
36 if name == '?': name = '__main__' # ...it just reads better
37 print ' %s called by %s (%s: %d)' % (at, name, file, line)
38 at = name # get ready for next iter
39
40 # print '-'*40
41 # print stack
42
43 # print '-'*40
44 # traceback.print_stack()
45
46 # ------------------------------------------------------------------------------
47 # ------------------------------------------------------------------------------
48
49 # test
50 if __name__ == '__main__':
51 def aaa():
52 bbb()
53
54 def bbb():
55 pass
56 pass
57 ccc()
58 pass
59
60 def ccc():
61 fmWhence(2)
62 pass
63 pass
64
65 aaa()
66
67 # ------------------------------------------------------------------------------
68 # ------------------------------------------------------------------------------
69 # ------------------------------------------------------------------------------