简体   繁体   English

Python:调用方的__file__

[英]Python: __file__ of the caller

I want to define a utility function f() in my module m such that 我想在模块m定义一个效用函数f()

  1. if mf() is invoked in /foo/a.py , it returns /foo/a.py 如果在/foo/a.py调用mf() ,则返回/foo/a.py
  2. if mf() invoked in /bar/baz/b.py , it returns /bar/baz/b.py 如果在/bar/baz/b.py调用了mf() ,则返回/bar/baz/b.py

Intuitively I'd explain f() as "it returns __file__ of the caller" but how can I really implement that (if possible at all?) 直观地讲,我将f()解释为“它返回了调用者的__file__ ”,但我该如何真正实现它(如果可能的话)?

Note def f(): return __file__ returns /path/to/m.py wherever I call mf() and that's not what I want. 注意def f(): return __file__无论我在哪里调用mf()返回/path/to/m.py ,这不是我想要的。

some.py: some.py:

m.f()

m.py: m.py:

import inspect
import os

def f():
    return os.path.relpath(
            inspect.stack()[1][1],
            basePath)
    # returns path to caller file relative to some basePath

__file__ is an attribute of the module loaded. __file__是加载的模块的属性。 So m.__file__ will always give the path of the file from which m was loaded. 因此, m.__file__将始终提供从中加载m的文件的路径。 To make it work for any module, you should call the attribute for that particular module. 为了使它适用于任何模块,应调用该特定模块的属性。

import module

def f(m): return m.__file__

print f(module)

Take a look at the inspect module. 看一下inspect模块。 It has a handy stack() method that returns the entire call stack, each element of which includes the filename. 它有一个方便的stack()方法 ,该方法返回整个调用堆栈,该堆栈的每个元素都包含文件名。 You just need to extract the last one. 您只需要提取最后一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM