获取Python中调用函数模块的__name__
假设 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”)的 /code> 属性。 如何才能做到这一点?
Suppose myapp/foo.py
contains:
def info(msg):
caller_name = ????
print '[%s] %s' % (caller_name, msg)
And myapp/bar.py
contains:
import foo
foo.info('Hello') # => [myapp.bar] Hello
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
查看检查模块:
inspect.stack()
将返回堆栈信息。在函数内部,
inspect.stack()[1]
将返回调用者的堆栈。 从那里,您可以获得有关调用者的函数名称、模块等的更多信息。有关详细信息,请参阅文档:
http://docs.python.org/library/inspect.html
另外,Doug Hellmann 在他的 PyMOTW 系列中对检查模块有一篇很好的文章:
http://pymotw.com/2/inspect/index.html#module-inspect
编辑:这里有一些代码可以完成您的任务我想:
Check out the inspect module:
inspect.stack()
will return the stack information.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
Also, Doug Hellmann has a nice writeup of the inspect module in his PyMOTW series:
http://pymotw.com/2/inspect/index.html#module-inspect
EDIT: Here's some code which does what you want, I think:
面对类似的问题,我发现 sys 模块中的 sys._current_frames() 包含有趣的信息,可以为您提供帮助,而无需导入检查,至少在特定用例中是这样。
然后,您可以使用 f_back “向上移动”:
对于文件名,您也可以使用 f.f_back.f_code.co_filename,如上面 Mark Roddy 所建议的。 我不确定此方法的限制和注意事项(多线程很可能是一个问题),但我打算在我的情况下使用它。
Confronted with a similar problem, I have found that sys._current_frames() from the sys module contains interesting information that can help you, without the need to import inspect, at least in specific use cases.
You can then "move up" using f_back :
For the filename you can also use f.f_back.f_code.co_filename, as suggested by Mark Roddy above. I am not sure of the limits and caveats of this method (multiple threads will most likely be a problem) but I intend to use it in my case.
我不建议这样做,但您可以通过以下方法完成您的目标:
然后按如下方式更新现有方法:
I don't recommend do this, but you can accomplish your goal with the following method:
Then update your existing method as follows:
对于我来说,下面的行足以获取呼叫者的姓名。
As for me, following line was enough to get callers'name.