cookiecaper cookiecaper -4 years ago 157
Python Question

Find path of module without importing in Python

I've seen several approaches for finding the path of a module by first importing it. Is there a way to do this without importing the module?

Answer Source

Using pkgutil module:

>>> import pkgutil
>>> package = pkgutil.get_loader("pip")
>>> package.filename
>>> package = pkgutil.get_loader("threading")
>>> package.filename
>>> package = pkgutil.get_loader("sqlalchemy.orm")
>>> package.filename

Using imp module:

>>> import imp
>>> imp.find_module('sqlalchemy')
(None, '/usr/lib/pymodules/python2.6/sqlalchemy', ('', '', 5))
>>> imp.find_module('pip')
(None, '/usr/local/lib/python2.6/dist-packages/pip-0.7.1-py2.6.egg/pip', ('', '', 5))
>>> imp.find_module('threading')
(<open file '/usr/lib/python2.6/', mode 'U' at 0x7fb708573db0>, '/usr/lib/python2.6/', ('.py', 'U', 1))

N.B: with imp module you can't do something like imp.find_module('sqlalchmy.orm')

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download