python3: 导入当前模块的文件名?

python3: name of the file which imports the current module?

假设我有一个名为 pymodule 的 python 模块,驻留在名为 pymodule.py.

的文件中

此外,假设 pymodule 被许多其他 python 程序导入,例如 program0.pyprogram1.pyprogram2.py

我可以在 pymodule.py 中编写任何代码来在运行时确定导入文件的名称吗?在此示例中,我们最终会得到 /path/to/program0.py/path/to/program1.py/path/to/program2.py,具体取决于这三个程序中的哪个是 运行.

当然,可能有一组嵌套的导入,其中导入了 pymodule,因此在一般情况下,我希望在以下位置获取整组导入祖先文件名运行时间。

在 python3 中有什么方法可以做到这一点吗?

非常感谢。

好的。我想到了。此代码可以位于 pymodule.py ...

# This is the "parent" of the current module.
# `sys._getframe(0)` would be `pymodule.py`.
f = sys._getframe(1)
while f is not None:
    print('filename: {}'.format(f.f_code.co_filename)
    f = f.f_back

如果 /path/to/program0.py 是 运行 ...

,它会打印出以下内容
filename: <frozen importlib._bootstrap>
filename: <frozen importlib._bootstrap_external>
filename: <frozen importlib._bootstrap>
filename: <frozen importlib._bootstrap>
filename: <frozen importlib._bootstrap>
filename: /path/to/program0.py

所以,我所要做的就是忽略以 <frozen ... 开头的项目,我将获得祖先文件名。这是一个函数...

def ancestor_importers():
    ancestors = []
    # Start with item number 2 here, because we're
    # inside of a function. Assume this function
    # resides at the top level of `pymodule`. If not,
    # the argument of sys._getframe(2) needs to be
    # adjusted accordingly.
    f = sys._getframe(2)
    while f is not None:
        fn = f.f_code.co_filename
        if not fn.startswith('<frozen '):
            ancestors.append(fn)
        f = f.f_back
    return ancestors