如何获得在计算机上安装的Python模块列表?


当前回答

有很多想法,我首先思考的是这两个:

pip

缺点:不总是安装

帮助(“模块”)

缺点:输出到控制台;使用损坏的模块(参见ubuntu…)可以段错误

我需要一个简单的方法,使用基本库,并与旧的python 2.x兼容

我明白了:listmodules.py

在2.5版本的文档源目录中隐藏了一个小脚本,它列出了Python安装的所有可用模块。

优点:

只使用imp、sys、os、re、time 设计用于运行Python 1.5.2及更新版本 源代码非常紧凑,所以你可以很容易地修补它,例如传递一个有bug的模块的异常列表(不要试图导入它们)

其他回答

这会有所帮助

在终端或IPython中输入:

help('modules')

then

In [1]: import                      #import press-TAB
Display all 631 possibilities? (y or n)
ANSI                   audiodev               markupbase
AptUrl                 audioop                markupsafe
ArgImagePlugin         avahi                  marshal
BaseHTTPServer         axi                    math
Bastion                base64                 md5
BdfFontFile            bdb                    mhlib
BmpImagePlugin         binascii               mimetools
BufrStubImagePlugin    binhex                 mimetypes
CDDB                   bisect                 mimify
CDROM                  bonobo                 mmap
CGIHTTPServer          brlapi                 mmkeys
Canvas                 bsddb                  modulefinder
CommandNotFound        butterfly              multifile
ConfigParser           bz2                    multiprocessing
ContainerIO            cPickle                musicbrainz2
Cookie                 cProfile               mutagen
Crypto                 cStringIO              mutex
CurImagePlugin         cairo                  mx
DLFCN                  calendar               netrc
DcxImagePlugin         cdrom                  new
Dialog                 cgi                    nis
DiscID                 cgitb                  nntplib
DistUpgrade            checkbox               ntpath

解决方案

不要与pip > 10.0一起使用!

我从Python脚本中获得一个类似于pip的冻结列表的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(但愿不会)安装的包。

我的用例

我将这个调用的结果添加到我的flask服务器,所以当我用http://example.com/exampleServer/environment调用它时,我得到了服务器的virtualenv上安装的包的列表。它使调试变得更加容易。

警告

我注意到这种技术的一个奇怪行为——当Python解释器在与setup.py文件相同的目录中调用时,它不会列出setup.py安装的包。

复制步骤:

Create a virtual environment
$ cd /tmp
$ virtualenv test_env
New python executable in test_env/bin/python
Installing setuptools, pip...done.
$ source test_env/bin/activate
(test_env) $ 
Clone a git repo with 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.

我们在/tmp/behave中有下面的setup.py:

(test_env) $ ls /tmp/behave/setup.py
/tmp/behave/setup.py
Install the python package from the git repo
(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文件。

我在文件中找不到任何关于这个问题的资料。也许我该为它打开一只虫子。

我需要找到AWS Lambda中默认可用的软件包的特定版本。我这样做是从这个页面的想法混搭。我要为子孙后代分享。

import pkgutil

__version__ = '0.1.1'

def get_ver(name):
    try:
        return str(__import__(name).__version__)
    except:
        return None

def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': [{
                   'path': m.module_finder.path,
                   'name': m.name,
                   'version': get_ver(m.name),
                 } for m in list(pkgutil.iter_modules())
                 #if m.module_finder.path == "/var/runtime" # Uncomment this if you only care about a certain path
                ],
    }

我发现提供的boto3库已经过时了,代码失败并不是我的错。我只需要添加boto3和botocore到我的项目。但如果没有这个,我可能会一直在想我的代码很糟糕。

{
  "statusCode": 200,
  "body": [
    {
      "path": "/var/task",
      "name": "lambda_function",
      "version": "0.1.1"
    },
    {
      "path": "/var/runtime",
      "name": "bootstrap",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "boto3",
      "version": "1.9.42"
    },
    {
      "path": "/var/runtime",
      "name": "botocore",
      "version": "1.12.42"
    },
    {
      "path": "/var/runtime",
      "name": "dateutil",
      "version": "2.7.5"
    },
    {
      "path": "/var/runtime",
      "name": "docutils",
      "version": "0.14"
    },
    {
      "path": "/var/runtime",
      "name": "jmespath",
      "version": "0.9.3"
    },
    {
      "path": "/var/runtime",
      "name": "lambda_runtime_client",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "lambda_runtime_exception",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "lambda_runtime_marshaller",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "s3transfer",
      "version": "0.1.13"
    },
    {
      "path": "/var/runtime",
      "name": "six",
      "version": "1.11.0"
    },
    {
      "path": "/var/runtime",
      "name": "test_bootstrap",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "test_lambda_runtime_client",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "test_lambda_runtime_marshaller",
      "version": null
    },
    {
      "path": "/var/runtime",
      "name": "urllib3",
      "version": "1.24.1"
    },
    {
      "path": "/var/lang/lib/python3.7",
      "name": "__future__",
      "version": null
    },
...

我所发现的也与他们官方公布的有所不同。在撰写本文时:

操作系统-亚马逊Linux AMI - amzn-ami-hvm-2017.03.1.20170812-x86_64-gp2 Linux内核- 4.14.77-70.59.amzn1.x86_64 AWS SDK for JavaScript - 2.290.0\ Python SDK (Boto 3) - 3-1.7.74 botocore-1.10.74

作品不考虑Pip版本

在python编辑器或IPython中运行以下命令:

import pkg_resources
installed_packages = {d.project_name: d.version for d in pkg_resources.working_set}
print(installed_packages)

阅读其他答案并将这个组合组合在一起,这是Python中最快和最简单的方法。

找到特定的包

你可以很方便地从词典中获取条目。

安装packages[‘pandas’]>> 1.16.4'

善用Pip List

pip列表将在你的jupyter笔记本中运行,简化了“快速检查” 与其他实用程序(如grep)结合使用(如果已安装) 例如,PIP列表| grep pandas将为您提供当前的pandas版本

PIP冻结可以找到所有的包,但是你可以简单地写下面的命令来列出python包所在的所有路径。

>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']