python quickie : retrace function steps?
Jeff Epler
jepler at unpythonic.net
Wed Aug 20 12:39:36 EDT 2003
On Wed, Aug 20, 2003 at 09:20:29AM -0700, Matt Smith wrote:
> 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?
Python has sys._getframe, and various frame-oriented functions in the
inspect module that build on sys._getframe.
$ cat /tmp/smith.py
from __future__ import generators
import inspect
try: enumerate
except NameError:
def enumerate(l):
idx = 0
for item in l:
yield idx, item
idx += 1
def f(): g()
def g(): h()
def h():
print_callers()
def print_callers():
for record in inspect.getouterframes(inspect.currentframe(1), 2):
print "%s() at %s:%d" % (record[3], record[1], record[2])
for idx, line in enumerate(record[4]):
print "%03d: %s" % ( idx + record[2] - 1, line.strip("\n"))
print
# Let's show something interesting
f()
$ python /tmp/smith.py
h() at /tmp/smith.py:18
017: def h():
018: print_callers()
g() at /tmp/smith.py:15
014:
015: def g(): h()
f() at /tmp/smith.py:13
012:
013: def f(): g()
?() at /tmp/smith.py:28
027: # Let's show something interesting
028: f()
Jeff
More information about the Python-list
mailing list