本文介绍了无需在 Python 中导入即可查找模块的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经看到了几种通过首先导入来查找模块路径的方法.有没有办法在不导入模块的情况下做到这一点?
解决方案
使用 pkgutil模块:
>>>导入 pkgutil>>>package = pkgutil.get_loader("pip")>>>包.文件名'/usr/local/lib/python2.6/dist-packages/pip-0.7.1-py2.6.egg/pip'>>>package = pkgutil.get_loader("线程")>>>包.文件名'/usr/lib/python2.6/threading.py'>>>package = pkgutil.get_loader("sqlalchemy.orm")>>>包.文件名'/usr/lib/pymodules/python2.6/sqlalchemy/orm'使用 imp 模块:
>>>进口进口>>>imp.find_module('sqlalchemy')(无, '/usr/lib/pymodules/python2.6/sqlalchemy', ('', '', 5))>>>imp.find_module('pip')(无, '/usr/local/lib/python2.6/dist-packages/pip-0.7.1-py2.6.egg/pip', ('', '', 5))>>>imp.find_module('线程')(<打开文件 '/usr/lib/python2.6/threading.py', 模式 'U' at 0x7fb708573db0>, '/usr/lib/python2.6/threading.py', ('.py', 'U', 1))注意:使用 imp 模块,你不能做类似imp.find_module('sqlalchmy.orm')
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?
解决方案
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')
这篇关于无需在 Python 中导入即可查找模块的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!