tags:

views:

54

answers:

1

I need to get the caller info (what file/what line) from callee. I learned that I can use inpect module for that for purposes, but not exactly how.

How to get those info with inspect? Or is there any other way to get the info?

import inspect

print __file__
c=inspect.currentframe()
print c.f_lineno

def hello():
    print inspect.stack
    ?? what file called me in what line?

hello()
+3  A: 

The caller's frame is one frame higher than the current frame. You can use inspect.getouterframes to get the caller's frame, plus the filename and line number.

#!/usr/bin/env python
# coding: utf-8

import inspect

def hello():
    frame,filename,line_number,function_name,lines,index=\
        inspect.getouterframes(inspect.currentframe())[1]
    print(frame,filename,line_number,function_name,lines,index)
hello()

# (<frame object at 0x8ba7254>, '/home/unutbu/pybin/test.py', 10, '<module>', ['hello()\n'], 0)
unutbu
@unutbu : thanks for the answer. How can I get the caller's caller?
prosseek
@prosseek: To get the caller's caller, just change the index `[1]` to `[2]`. (`inspect.getouterframes` returns a list of frames...). Python is beautifully organized.
unutbu