2012-12-04 36 views
11

为例,a.boo方法调用b.foo方法。在b.foo方法,我怎样才能得到一个文件的文件名(我不想通过__file__b.foo法)...如何获取调用者的文件名,方法名称以python

+0

感谢您的回答,我在这里找到的对我来说是最好的:http://stackoverflow.com/questions/3711184/how-to-use-inspect-to-get-the-callers-info-from -callee –

回答

18

可以使用inspect模块来实现这一目标:

frame = inspect.stack()[1] 
module = inspect.getmodule(frame[0]) 
filename = module.__file__ 
1

可以使用traceback模块:

import traceback 

,并可以打印回溯这样的:

print traceback.format_exc() 

我多年没用过这个,但这应该足以让你开始。