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

河马人

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

此外,假设pymodule由多个其它Python程序的进口,例如program0.pyprogram1.py,和program2.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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何导入文件名中带有句点的Python 3模块?

获取当前ES模块的文件名

Python:如何将没有python文件名的模块作为子模块导入?

从不同文件导入 Python3 模块

Python3 Linux中的文件名编码问题

如何在 Python 中使用导入模块的内容而不必每次都写模块的文件名?

Python中是否可以保证模块文件名中扩展名的导入顺序?

模块导入失败,除非在当前目录中 - Python3

不支持按文件名导入Gunicorn(模块)

python3模块导入/命名难题

Python3 模块导入混淆

在python3中导入模块

如何阻止Python“导入”也导入文件名?

python2自动完成BASH shell上的文件名,python3不会

Python-导入模块的文件名称不同?

如何从python3的子文件夹中导入模块(空__init__.py)

如何从python3的子文件夹中导入模块(空__init__.py)

如何在Windows中的python3中导入文件/模块?

如何获取在Python中导入文件的文件名

导入文件名是灰色的

在python中,如何导入文件名以数字开头

在python中,如何导入文件名以数字开头

<未知>:0:错误:打开模块“ Swift”的导入文件:文件名太长

设置Python模块的属性而不是文件名

OSError: [WinError 123] python3 中的文件名、目录名或卷标语法不正确

Python3将模块从文件夹导入到另一个文件夹

无法在python3中导入pymysql模块

在 Python3 中导入模块时出错

导入模块错误python3 xubuntu 19.04