如何获取尝试在python 3.x中导入当前模块(模块的首次导入)的模块名称?

时间:2019-10-10 08:00:47

标签: python python-3.x python-import

例如:有2个文件
a.py

import b
...

b.py

print('???')  # here I want to figure out which module called me
# this module could be imported from different modules/places not even from expected places.
# there is no certain purpose to use such information, just try to find out is it possible.

问题:

是否可以找出将fisrt导入另一个模块的模块名称?

PS:

不能像here那样进行修补。 b.py可以分别导入到第三方模块中。

1 个答案:

答案 0 :(得分:-1)

在您的b.py文件中添加以下代码,然后您将获得导入b的文件的名称。

import sys, os

def getCalledModuleName():
    try:
        sFile = os.path.abspath(sys.modules['__main__'].__file__)
        names = sFile.split('\\')
        length = len(names)
        name = names[length-1]

    except:
        sFile = sys.executable
        names = sFile.split('\\')
        length = len(names)
        name = names[length - 1]
    return name


if __name__=='__main__':
    print('Main Function Called')
else:
    print('Imported as Module')
    print(getCalledModuleName())