在Python中获取调用函数模块的__name__ [英] Get __name__ of calling function's module in Python
问题描述
假设myapp/foo.py
包含:
def info(msg):
caller_name = ????
print '[%s] %s' % (caller_name, msg)
myapp/bar.py
包含:
import foo
foo.info('Hello') # => [myapp.bar] Hello
在这种情况下,我希望将caller_name
设置为调用函数模块的__name__
属性(即"myapp.foo").该怎么办?
I want caller_name
to be set to the __name__
attribute of the calling functions' module (which is 'myapp.foo') in this case. How can this be done?
推荐答案
检出检查模块:
inspect.stack()
将返回堆栈信息.
在函数内部,inspect.stack()[1]
将返回调用者的堆栈.从那里,您可以获取有关调用者的函数名称,模块等的更多信息.
Inside a function, inspect.stack()[1]
will return your caller's stack. From there, you can get more information about the caller's function name, module, etc.
有关详细信息,请参阅文档:
See the docs for details:
http://docs.python.org/library/inspect.html
此外,道格·海尔曼(Doug Hellmann)在其PyMOTW系列中对检查模块进行了很好的撰写:
Also, Doug Hellmann has a nice writeup of the inspect module in his PyMOTW series:
http://pymotw.com/2/inspect/index.html #module-inspect
我认为这是一些您想要执行的代码:
Here's some code which does what you want, I think:
import inspect
def info(msg):
frm = inspect.stack()[1]
mod = inspect.getmodule(frm[0])
print '[%s] %s' % (mod.__name__, msg)
这篇关于在Python中获取调用函数模块的__name__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!