如何从执行但未声明的函数中获取模块的文件路径? [英] How to get the file path of a module from a function executed but not declared in it?
本文介绍了如何从执行但未声明的函数中获取模块的文件路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我想要当前模块的路径,我将使用__file__
.
If I want the path of the current module, I'll use __file__
.
现在让我们说我想要一个函数将其返回.我做不到:
Now let's say I want a function to return that. I can't do:
def get_path():
return __file__
因为它将返回已在其中声明该函数的模块的路径.
Because it will return the path of the module the function has been declared in.
即使函数不是在模块的根目录而是在任何嵌套级别调用,我也需要它工作.
I need it to work even if the function is not called at the root of the module but at any level of nesting.
推荐答案
这就是我要这样做的方式:
This is how I would do it:
import sys
def get_path():
namespace = sys._getframe(1).f_globals # caller's globals
return namespace.get('__file__')
这篇关于如何从执行但未声明的函数中获取模块的文件路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文