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?
You can manually go and check the PYTHONPATH variable contents to find the directories from where these built in modules are being imported. Running "python -v"from the command line tells you what is being imported and from where. This is useful if you want to know the location of built in modules.
If you change __path__ , you can force the interpreter to look in a different directory for modules belonging to that package. This would allow you to, e.g., load different versions of the same module based on runtime conditions.
Inside the package, you can find your modules by directly using __loader__ of course. That only works for modules, not packages. Try it on Python's logging package to see what I mean.
Using pkgutil module:
>>> import pkgutil >>> package = pkgutil.get_loader("pip") >>> package.filename '/usr/local/lib/python2.6/dist-packages/pip-0.7.1-py2.6.egg/pip' >>> package = pkgutil.get_loader("threading") >>> package.filename '/usr/lib/python2.6/threading.py' >>> package = pkgutil.get_loader("sqlalchemy.orm") >>> package.filename '/usr/lib/pymodules/python2.6/sqlalchemy/orm'
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/threading.py', mode 'U' at 0x7fb708573db0>, '/usr/lib/python2.6/threading.py', ('.py', 'U', 1))
N.B: with imp module you can't do something like imp.find_module('sqlalchmy.orm')
For python3 imp
is deprecated. Use pkgutil (as seen above) or for Python 3.4+ use importlib.util.find_spec:
>>> import importlib >>> spec = importlib.util.find_spec("threading") >>> spec.origin '/usr/lib64/python3.6/threading.py'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With