Find path of module without importing in Python

后端 未结 3 1584
时光取名叫无心
时光取名叫无心 2020-12-01 02:17

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?

相关标签:
3条回答
  • 2020-12-01 02:27

    You might want to try running this in your interpreter:

    >>> import sys
    >>> sys.modules['codecs'].__file__ # codecs is just an example
    '/usr/lib/python2.7/codecs.pyc'
    
    0 讨论(0)
  • 2020-12-01 02:32

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

    0 讨论(0)
  • 2020-12-01 02:38

    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'
    
    0 讨论(0)
提交回复
热议问题