例如:有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导入另一个模块的模块名称?
不能像here那样进行修补。 b.py
可以分别导入到第三方模块中。
答案 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())