如何获取本地安装的Python模块列表?

如何获取本地安装的Python模块列表?,python,module,pip,Python,Module,Pip,我想获得Python模块的列表,这些模块在我的Python安装(UNIX服务器)中 如何获得安装在计算机中的Python模块列表 help('modules') 在pythonshell/prompt中。现在,我自己尝试了这些方法,得到了广告上所宣传的:所有模块 唉,你真的不太关心stdlib,你知道安装python会得到什么 真的,我想要我安装的东西 令人惊讶的是,实际上效果很好的是: pip freeze 它返回: Fabric==0.9.3 apache-libcloud==0.4.0

我想获得Python模块的列表,这些模块在我的Python安装(UNIX服务器)中

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

help('modules')

在pythonshell/prompt中。

现在,我自己尝试了这些方法,得到了广告上所宣传的:所有模块

唉,你真的不太关心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
我之所以说“令人惊讶”,是因为包安装工具正是人们希望找到此功能的地方,虽然不是以“冻结”为名,但python打包非常奇怪,以至于我惊讶于此工具的意义。pip0.8.2,python2.7

  • 在中,您可以键入“
    import
    Tab”

  • 在标准Python解释器中,可以键入“
    help('modules')

  • 在命令行中,您可以使用
    模块

  • 在脚本中,调用


使用


我只是用它来查看当前使用的模块:

import sys as s
s.modules.keys()
它显示了python上运行的所有模块

对于所有内置模块,请使用:

s.modules

这是一个包含所有模块和导入对象的dict。

我在OS X上遇到了一个自定义安装的python 2.7。它要求X11列出已安装的模块(使用help和pydoc)

为了能够在不安装X11的情况下列出所有模块,我将pydoc作为http服务器运行,即:

pydoc -p 12345

然后可以将Safari指向
http://localhost:12345/
查看所有模块。

除了使用
pip冻结
之外,我一直在虚拟环境中安装。

自pip版本1.3以来,您可以访问:

pip list
$ cd /tmp
$ virtualenv test_env
New python executable in test_env/bin/python
Installing setuptools, pip...done.
$ source test_env/bin/activate
(test_env) $ 

这似乎是“pip freeze”的语法糖。它将列出您的安装或virtualenv所特有的所有模块及其版本号。不幸的是,它没有显示任何模块的当前版本号,也没有为您洗碗或擦鞋。

在普通shell中,只需使用即可

pydoc modules
如果您已安装了,还可以使用

$conda list

除了上面描述的解决方案之外。

如果我们需要在Python shell中列出已安装的软件包,我们可以使用
help
命令,如下所示

>>> help('modules package')
  • 要获取所有可用模块,请运行
    sys.modules
  • 要获取所有已安装的模块(阅读:由
    pip安装
    ),您可以查看
    pip.get\u installed\u 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
    
    解决方案 不要与pip>10.0一起使用! 我从Python脚本中获得类似于pip冻结的列表的50美分:

    导入pip
    installed\u packages=pip.get\u installed\u发行版()
    已安装的软件包\u列表=已排序([%s==%s”%(i.key,i.version)
    对于已安装的软件包中的i])
    打印(已安装的软件包列表)
    
    作为一个(太长的)单层衬里:

    已排序([%s==%s”%(i.key,i.version)用于pip.get\u installed\u distributions()
    
    给予:

    ['behave==1.2.4'、'enum34==1.0'、'flask==0.10.1'、'itsDanger==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元数据==0.1'、'vioozer用户服务器==0.1',
    'werkzeug==0.9.4']
    
    范围 此解决方案适用于系统范围或虚拟环境范围,并涵盖由
    setuptools
    pip
    和()
    easy\u install
    安装的软件包

    $ cd /tmp
    $ virtualenv test_env
    New python executable in test_env/bin/python
    Installing setuptools, pip...done.
    $ source test_env/bin/activate
    (test_env) $ 
    
    我的用例 我将此调用的结果添加到我的flask服务器,因此当我使用
    http://example.com/exampleServer/environment
    我得到了安装在服务器virtualenv上的软件包列表。它使调试变得更加容易

    警告 我注意到这种技术有一种奇怪的行为——当Python解释器在与
    setup.py
    文件相同的目录中调用时,它不会列出由
    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.
    
    复制步骤: 创建虚拟环境
    $ cd /tmp
    $ virtualenv test_env
    New python executable in test_env/bin/python
    Installing setuptools, pip...done.
    $ source test_env/bin/activate
    (test_env) $ 
    
    使用
    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
    中有behave的
    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.
    
    (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
    如果我们从
    /tmp/behave
    第二个示例中缺少
    behave==1.2.5a1
    ,因为工作目录包含
    behave
    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.
    

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

    在windows上,在cmd中输入这个

    c:\python\libs>python -m pip freeze
    

    pipfreeze查找所有包都要做,但是可以简单地编写以下命令来列出python包所在的所有路径

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

    此解决方案主要基于模块
    importlib
    pkgutil
    ,并与CPython 3.4和CPython 3.5配合使用,但不支持CPython 2


    解释

  • sys.builtin\u module\u name
    -命名所有内置模块(看我的答案)
  • pkgutil.iter_modules()
    -返回有关所有可用模块的信息
  • importlib.util.find_spec()
    -返回有关导入模块的信息(如果存在)
  • BuiltinImporter
    -内置模块的导入程序()
  • SourceFileLoader
    -标准Python模块的导入程序(默认情况下具有扩展名*.py)()
  • 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()
    

    用法

    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\u modules\u info.py
    ------------------------------------------
    
    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
    -------------------------------------------  --------------  ------
    
    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
                    ],
        }
    
    {
      "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
        },
    ...
    
    pip list
    
    pip freeze
    
    import pip
    pip.main(['list])  # this will print all the packages
    
    help('modules')
    
    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 install pkgutil
    
    import pkgutil
    
    for i in pkgutil.iter_modules(None): # returns a tuple (path, package_name, ispkg_flag)
        print(i[1]) #or you can append it to a list
    
    multiprocessing
    netrc
    nntplib
    ntpath
    nturl2path
    numbers
    opcode
    pickle
    pickletools
    pipes
    pkgutil
    
    import pkg_resources
    installed_packages = {d.project_name: d.version for d in pkg_resources.working_set}
    print(installed_packages)
    
    pip install pip-chill 
    pip-chill