How can I get the file path of a module imported in python. I am using Linux (if it matters).
Eg: if I am in my home dir and import a module, it should return back the full path of my home directory.
I have been using this method, which applies to both non-built-in and built-in modules:
def showModulePath(module):
if (hasattr(module, '__name__') is False):
print 'Error: ' + str(module) + ' is not a module object.'
return None
moduleName = module.__name__
modulePath = None
if imp.is_builtin(moduleName):
modulePath = sys.modules[moduleName];
else:
modulePath = inspect.getsourcefile(module)
modulePath = '<module \'' + moduleName + '\' from \'' + modulePath + 'c\'>'
print modulePath
return modulePath
Example:
Utils.showModulePath(os)
Utils.showModulePath(cPickle)
Result:
<module 'os' from 'C:\SciSoft\WinPython-64bit-2.7.10.3\python-2.7.10.amd64\lib\os.pyc'>
<module 'cPickle' (built-in)>