如果需要当前模块的路径,将使用__file__
。
现在,我想让一个函数返回它。我做不到:
def get_path():
return __file__
因为它将返回已在其中声明该函数的模块的路径。
即使函数不是在模块的根目录而是在任何嵌套级别调用,我都需要它起作用。
这就是我的做法:
import sys
def get_path():
namespace = sys._getframe(1).f_globals # caller's globals
return namespace.get('__file__')
在这种情况下,从globals
字典中获取它:
def get_path():
return globals()['__file__']
根据评论进行编辑:给定以下文件:
# a.py
def get_path():
return 'Path from a.py: ' + globals()['__file__']
# b.py
import a
def get_path():
return 'Path from b.py: ' + globals()['__file__']
print get_path()
print a.get_path()
运行此命令将为我提供以下输出:
C:\workspace>python b.py
Path from b.py: b.py
Path from a.py: C:\workspace\a.py
在绝对/相对路径旁边有所不同(为简洁起见,让我们省略),对我来说看起来不错。
我找到了一种使用检查模块的方法。我对这个解决方案还可以,但是如果有人找到一种方法而又不转储整个stacktrace,它会更干净,我会很感激地接受他的回答:
def get_path():
frame, filename, line_number, function_name, lines, index =\
inspect.getouterframes(inspect.currentframe())[1]
return filename