Python 获取在执行第一个模块时位于第三个模块中的函数中导入的第二个模块的文件路径
我在Python 获取在执行第一个模块时位于第三个模块中的函数中导入的第二个模块的文件路径,python,python-3.x,Python,Python 3.x,我在X.py中导入模块Y.py,在Z.py模块中有一个函数my_func(),我在Y.py中导入该函数时,如何在my_func()中打印Y.py的路径,而不将任何参数传递给my_func() 模块X # this is module X import Y #some code 模块Y # this is module Y from Z import * my_func() #some code 模块Z # this is module Z def my_func() pri
X.py
中导入模块Y.py
,在Z.py
模块中有一个函数my_func()
,我在Y.py
中导入该函数时,如何在my_func()
中打印Y.py
的路径,而不将任何参数传递给my_func()
模块X
# this is module X
import Y
#some code
模块Y
# this is module Y
from Z import *
my_func()
#some code
模块Z
# this is module Z
def my_func()
print("the path of Y module is: ") # here I want to print the path of Y.py
# do something with the path of Y.py
当我执行X.py时,它应该打印Y.py的路径,我尝试使用os.getcwd()
但是它给我的是X.py的路径而不是Y.py的路径您使用模块对象的属性:
import Y
def my_func():
path = Y.__file__
您可以使用模块对象的属性:
import Y
def my_func():
path = Y.__file__
为什么您认为这很重要?您可以使用
inspect
来识别谁导入了您。不过,你为什么需要这个?你只是把我的神经元都包在一堆哦,天哪,这让我很困惑为什么你认为这很重要?你可以用inspect
来辨别是谁引进了你。不过,你为什么需要这个?你只是把我的神经元都包在一堆哦,天哪,真让人困惑