Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find path of module without importing in Python

Tags:

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?

like image 413
jeffcook2150 Avatar asked Jan 14 '11 16:01

jeffcook2150


People also ask

How do I find where a Python module is located?

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.

What is __ path __ in Python?

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.

How do I find out what modules are in a Python package?

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.


2 Answers

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')

like image 58
mouad Avatar answered Sep 17 '22 20:09

mouad


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' 
like image 27
Bryce Guinta Avatar answered Sep 16 '22 20:09

Bryce Guinta