Skip to main content
 首页 » 编程设计

python之如何找出作为 Python 程序开头的文件

2024年10月24日9傻小

<分区>

假设我有一个包含至少两个文件的程序,magic.py 是 herebemagic 模块的一部分...

def foo(): 
    # This line is what my question will be all about 
    pass 

...和启动程序的 main.py:

import os 
from herebemagic import magic 
print("This is where this file lies: %s" % (repr(os.path.abspath(__file__)), )) 
magic.foo() 

如前所述,查找模块的文件及其所在路径非常简单。但是,我如何在 magic.py 中获取对 main.py 模块的引用(由解释器调用的模块,不一定是直接导入 herebemagic 的模块),以便我可以获取其文件?

当然我可以在 main.py 中弄清楚,然后将它传递给 foo(),但实际上两者之间可以有任意数量的模块,在我的例子中,它是很难把它传递下去(我用 importlib 加载了很多模块,目前信息只与其中一个模块相关)。或者我可以使用一个内置的,但这是一个没有人愿意乱扔垃圾的命名空间。