import sys
def get_caller(ext=False):
""" Get the caller of the caller of this function. If the optional ext parameter is given, returns the line's text as well. """
f=sys._getframe(2)
s=(f.f_code.co_filename, f.f_lineno)
del f
if ext:
import linecache
s=(s[0], s[1], linecache.getline(s[0], s[1]))
return s
def post_event(e):
caller=get_caller(True)
print "Event %r posted from %r"%(e, caller)
## Testing the functions.
def q():
post_event("baz")
post_event("foo")
print "Hello!"
q()
结果是
Event 'foo' posted from ('getcaller.py', 20, 'post_event("foo")\n')
Hello!
Event 'baz' posted from ('getcaller.py', 17, '\tpost_event("baz")\n')