Skip to content Skip to sidebar Skip to footer

Get Path Of Importing Module

I have two python files: main.py and imported.py. I want to import imported.py into main.py but I want access to the path of main.py in the file imported.py. That is I want acces

Solution 1:

I don't know any "importing" notification hook. You can achieve some what similar thing by explicitly calling a function into imported module:

#main.pyimport imp
import sys
import os

imported = imp.load_source('imported', "/absolute/path/to/imported.py")
imported.doSomething(os.path.abspath(sys.modules[__name__].__file__))

#imported.pydefdoSomething(importing_path):
   print ("Importing path: ", importing_path)
   pass

Solution 2:

Solution received in comments from ekhumoro:

#main.py
import imp
imported = imp.load_source('imported', "/absolute/path/to/imported.py")


#imported.py
pathToImportingModule=os.path.abspath(sys.modules['__main__'].__file__)    
doSomethingWithPath(pathToImportingModule)

Post a Comment for "Get Path Of Importing Module"