我想获得一个Python模块列表,这些模块在我的Python安装(UNIX服务器)中.
如何获得计算机中安装的Python模块列表?
help('modules')
在Python shell /提示符下.
pip freeze
从Python脚本中获取类似列表的50美分:
import pip
installed_packages = pip.get_installed_distributions()
installed_packages_list = sorted(["%s==%s" % (i.key, i.version)
for i in installed_packages])
print(installed_packages_list)
作为(太长)一个班轮:
sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])
赠送:
['behave==1.2.4', 'enum34==1.0', 'flask==0.10.1', 'itsdangerous==0.24',
'jinja2==2.7.2', 'jsonschema==2.3.0', 'markupsafe==0.23', 'nose==1.3.3',
'parse-type==0.3.4', 'parse==1.6.4', 'prettytable==0.7.2', 'requests==2.3.0',
'six==1.6.1', 'vioozer-metadata==0.1', 'vioozer-users-server==0.1',
'werkzeug==0.9.4']
此解决方案适用于系统范围或虚拟环境范围,并涵盖由setuptools
(pip
和上帝禁止)安装的软件包easy_install
.
我将这个调用的结果添加到我的烧瓶服务器,所以当我调用它时,http://example.com/exampleServer/environment
我得到服务器的virtualenv上安装的软件包列表.它使调试变得更加容易.
我注意到这种技术的奇怪行为 - 当Python解释器在与setup.py
文件相同的目录中调用时,它不会列出安装的包setup.py
.
$ cd /tmp $ virtualenv test_env New python executable in test_env/bin/python Installing setuptools, pip...done. $ source test_env/bin/activate (test_env) $克隆一个git repo
setup.py
(test_env) $ git clone https://github.com/behave/behave.git Cloning into 'behave'... remote: Reusing existing pack: 4350, done. remote: Total 4350 (delta 0), reused 0 (delta 0) Receiving objects: 100% (4350/4350), 1.85 MiB | 418.00 KiB/s, done. Resolving deltas: 100% (2388/2388), done. Checking connectivity... done.
我们必须表现的setup.py
在/tmp/behave
:
(test_env) $ ls /tmp/behave/setup.py /tmp/behave/setup.py从git repo安装python包
(test_env) $ cd /tmp/behave && pip install . running install ... Installed /private/tmp/test_env/lib/python2.7/site-packages/enum34-1.0-py2.7.egg Finished processing dependencies for behave==1.2.5a1
/tmp
>>> import pip >>> sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()]) ['behave==1.2.5a1', 'enum34==1.0', 'parse-type==0.3.4', 'parse==1.6.4', 'six==1.6.1'] >>> import os >>> os.getcwd() '/private/tmp'
/tmp/behave
>>> import pip >>> sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()]) ['enum34==1.0', 'parse-type==0.3.4', 'parse==1.6.4', 'six==1.6.1'] >>> import os >>> os.getcwd() '/private/tmp/behave'
behave==1.2.5a1
在第二个示例中缺少,因为工作目录包含behave
的setup.py
文件.
我在文档中找不到任何对此问题的引用.也许我会为它打开一个错误.
现在,我尝试了这些方法,并且我得到了所宣传的内容:所有模块.
唉,你真的不太关心stdlib,你知道你用python安装得到了什么.
真的,我想要我安装的东西.
实际上,令人惊讶的是,工作得很好的是:
pip freeze
返回的是:
Fabric==0.9.3 apache-libcloud==0.4.0 bzr==2.3b4 distribute==0.6.14 docutils==0.7 greenlet==0.3.1 ipython==0.10.1 iterpipes==0.4 libxml2-python==2.6.21
我说"令人惊讶",因为软件包安装工具是人们期望找到这个功能的确切位置,虽然不是名为'freeze',但python包装是如此奇怪,我很惊讶这个工具是有道理的.Pip 0.8.2,Python 2.7.
在ipython
你可以输入" import
Tab".
在标准Python解释器中,您可以键入" help('modules')
".
在命令行,您可以使用.pydoc
modules
在脚本中,调用pkgutil.iter_modules()
.
从pip 1.3版开始,您就可以访问:
pip list
这似乎是"pip冻结"的语法糖.它将列出特定于您的安装或virtualenv的所有模块及其版本号.不幸的是,它没有显示任何模块的当前版本号,也没有洗碗或擦鞋.
我只是用它来查看当前使用的模块:
import sys as s s.modules.keys()
它显示了在python上运行的所有模块.
对于所有内置模块,请使用:
s.modules
哪个是包含所有模块和导入对象的dict.
在正常的shell中使用
pydoc modules
从第10点开始,接受的答案将不再适用.开发团队已删除对get_installed_distributions
例程的访问权限.在setuptools
做同样的事情中还有一个替代功能.这是与pip 10一起使用的替代版本:
import pkg_resources installed_packages = pkg_resources.working_set installed_packages_list = sorted(["%s==%s" % (i.key, i.version) for i in installed_packages]) print(installed_packages_list)
如果它在以前版本的pip中有效或不可用,请告诉我.
如果我们需要在Python shell中列出已安装的软件包,我们可以help
按如下方式使用该命令
>>help('modules package')
我通常pip list
用来获取包列表(带有版本).
当然,这也适用于虚拟环境.
使用pkgutil.iter_modules进行非常简单的搜索
from pkgutil import iter_modules a=iter_modules() while True: try: x=a.next() except: break if 'searchstr' in x[1]: print x[1]
我在OS X上遇到了一个自定义安装的python 2.7.它需要X11来列出安装的模块(使用help和pydoc).
为了能够在不安装X11的情况下列出所有模块,我将pydoc作为http-server运行,即:
pydoc -p 12345
然后可以指示Safari http://localhost:12345/
查看所有模块.
在Windows上,在cmd中输入
c:\python\libs>python -m pip freeze
这是受到亚当·马坦(Adam Matan)的回答(公认的)的启发:
import tabulate try: from pip import get_installed_distributions except: from pip._internal.utils.misc import get_installed_distributions tabpackages = [] for _, package in sorted([('%s %s' % (i.location, i.key), i) for i in get_installed_distributions()]): tabpackages.append([package.location, package.key, package.version]) print(tabulate.tabulate(tabpackages))
然后以以下形式打印出表格
19:33 pi@rpi-v3 [iot-wifi-2] ~/python$ python installed_packages.py ------------------------------------------- -------------- ------ /home/pi/.local/lib/python2.7/site-packages enum-compat 0.0.2 /home/pi/.local/lib/python2.7/site-packages enum34 1.1.6 /home/pi/.local/lib/python2.7/site-packages pexpect 4.2.1 /home/pi/.local/lib/python2.7/site-packages ptyprocess 0.5.2 /home/pi/.local/lib/python2.7/site-packages pygatt 3.2.0 /home/pi/.local/lib/python2.7/site-packages pyserial 3.4 /usr/local/lib/python2.7/dist-packages bluepy 1.1.1 /usr/local/lib/python2.7/dist-packages click 6.7 /usr/local/lib/python2.7/dist-packages click-datetime 0.2 /usr/local/lib/python2.7/dist-packages construct 2.8.21 /usr/local/lib/python2.7/dist-packages pyaudio 0.2.11 /usr/local/lib/python2.7/dist-packages tabulate 0.8.2 ------------------------------------------- -------------- ------
这样一来,您便可以轻松辨别使用和不安装时安装的软件包sudo
。
撇开笔记:我注意到,当我一次安装一个数据包而一次安装一次数据包时sudo
,一个优先,因此不会列出另一个数据包(仅显示一个位置)。我相信只会列出本地目录中的一个。这可以改善。
除了使用pip freeze
我一直在我的虚拟环境中安装蛋黄.
获取所有可用模块,运行 sys.modules
要获得所有已安装的模块(阅读:安装者pip
),您可以查看pip.get_installed_distributions()
为了第二个目的,示例代码:
import pip for package in pip.get_installed_distributions(): name = package.project_name # SQLAlchemy, Django, Flask-OAuthlib key = package.key # sqlalchemy, django, flask-oauthlib module_name = package._get_metadata("top_level.txt") # sqlalchemy, django, flask_oauthlib location = package.location # virtualenv lib directory etc. version = package.version # version number
此解决方案主要基于模块importlib
,pkgutil
并与CPython 3.4和CPython 3.5一起使用,但不支持CPython 2.
说明
sys.builtin_module_names
- 命名所有内置模块(在这里查看我的答案)
pkgutil.iter_modules()
- 返回有关所有可用模块的信息
importlib.util.find_spec()
- 返回有关导入模块的信息(如果存在)
BuiltinImporter
- 内置模块的导入器(docs)
SourceFileLoader
- 标准Python模块的导入程序(默认情况下具有扩展名*.py)(docs)
ExtensionFileLoader
- 作为共享库的模块的导入程序(在C或C++上编写)
完整代码
import sys import os import shutil import pkgutil import importlib import collections if sys.version_info.major == 2: raise NotImplementedError('CPython 2 is not supported yet') def main(): # name this file (module) this_module_name = os.path.basename(__file__).rsplit('.')[0] # dict for loaders with their modules loaders = collections.OrderedDict() # names`s of build-in modules for module_name in sys.builtin_module_names: # find an information about a module by name module = importlib.util.find_spec(module_name) # add a key about a loader in the dict, if not exists yet if module.loader not in loaders: loaders[module.loader] = [] # add a name and a location about imported module in the dict loaders[module.loader].append((module.name, module.origin)) # all available non-build-in modules for module_name in pkgutil.iter_modules(): # ignore this module if this_module_name == module_name[1]: continue # find an information about a module by name module = importlib.util.find_spec(module_name[1]) # add a key about a loader in the dict, if not exists yet loader = type(module.loader) if loader not in loaders: loaders[loader] = [] # add a name and a location about imported module in the dict loaders[loader].append((module.name, module.origin)) # pretty print line = '-' * shutil.get_terminal_size().columns for loader, modules in loaders.items(): print('{0}\n{1}: {2}\n{0}'.format(line, len(modules), loader)) for module in modules: print('{0:30} | {1}'.format(module[0], module[1])) if __name__ == '__main__': main()
用法
对于CPython3.5(截断)
$ python3.5 python_modules_info.py ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 30:------------------------------------------------------------------------------------------------------------------------------------------------------------------------ _ast | built-in _codecs | built-in _collections | built-in _functools | built-in _imp | None _io | built-in _locale | built-in _operator | built-in _signal | built-in _sre | built-in _stat | built-in _string | built-in _symtable | built-in _thread | built-in (****************************truncated*******************************) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 227: ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ __future__ | /usr/local/lib/python3.5/__future__.py _bootlocale | /usr/local/lib/python3.5/_bootlocale.py _collections_abc | /usr/local/lib/python3.5/_collections_abc.py _compat_pickle | /usr/local/lib/python3.5/_compat_pickle.py _compression | /usr/local/lib/python3.5/_compression.py _dummy_thread | /usr/local/lib/python3.5/_dummy_thread.py _markupbase | /usr/local/lib/python3.5/_markupbase.py _osx_support | /usr/local/lib/python3.5/_osx_support.py _pydecimal | /usr/local/lib/python3.5/_pydecimal.py _pyio | /usr/local/lib/python3.5/_pyio.py _sitebuiltins | /usr/local/lib/python3.5/_sitebuiltins.py (****************************truncated*******************************) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 64: ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ _bisect | /usr/local/lib/python3.5/lib-dynload/_bisect.cpython-35m-x86_64-linux-gnu.so _bz2 | /usr/local/lib/python3.5/lib-dynload/_bz2.cpython-35m-x86_64-linux-gnu.so _codecs_cn | /usr/local/lib/python3.5/lib-dynload/_codecs_cn.cpython-35m-x86_64-linux-gnu.so _codecs_hk | /usr/local/lib/python3.5/lib-dynload/_codecs_hk.cpython-35m-x86_64-linux-gnu.so _codecs_iso2022 | /usr/local/lib/python3.5/lib-dynload/_codecs_iso2022.cpython-35m-x86_64-linux-gnu.so (****************************truncated*******************************)
对于CPython3.4(截断)
$ python3.4 python_modules_info.py ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 54:------------------------------------------------------------------------------------------------------------------------------------------------------------------------ _ast | built-in _bisect | built-in _codecs | built-in _collections | built-in _datetime | built-in _elementtree | built-in _functools | built-in _heapq | built-in _imp | None _io | built-in _locale | built-in _md5 | built-in _operator | built-in _pickle | built-in _posixsubprocess | built-in _random | built-in (****************************truncated*******************************) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 246: ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ __future__ | /usr/lib/python3.4/__future__.py _bootlocale | /usr/lib/python3.4/_bootlocale.py _collections_abc | /usr/lib/python3.4/_collections_abc.py _compat_pickle | /usr/lib/python3.4/_compat_pickle.py _dummy_thread | /usr/lib/python3.4/_dummy_thread.py _markupbase | /usr/lib/python3.4/_markupbase.py _osx_support | /usr/lib/python3.4/_osx_support.py _pyio | /usr/lib/python3.4/_pyio.py (****************************truncated*******************************) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 44: ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ _bz2 | /usr/lib/python3.4/lib-dynload/_bz2.cpython-34m-x86_64-linux-gnu.so _codecs_cn | /usr/lib/python3.4/lib-dynload/_codecs_cn.cpython-34m-x86_64-linux-gnu.so _codecs_hk | /usr/lib/python3.4/lib-dynload/_codecs_hk.cpython-34m-x86_64-linux-gnu.so _codecs_iso2022 | /usr/lib/python3.4/lib-dynload/_codecs_iso2022.cpython-34m-x86_64-linux-gnu.so _codecs_jp | /usr/lib/python3.4/lib-dynload/_codecs_jp.cpython-34m-x86_64-linux-gnu.so _codecs_kr | /usr/lib/python3.4/lib-dynload/_codecs_kr.cpython-34m-x86_64-linux-gnu.so _codecs_tw | /usr/lib/python3.4/lib-dynload/_codecs_tw.cpython-34m-x86_64-linux-gnu.so _crypt | /usr/lib/python3.4/lib-dynload/_crypt.cpython-34m-x86_64-linux-gnu.so (****************************truncated*******************************)
试试这些
pip list
要么
pip freeze
如果您安装了anaconda python发行版,则也可以使用
$conda list
除了上述解决方案。