LoginSignup
72
80

More than 5 years have passed since last update.

pythonで現在の環境にインストールされているパッケージの一覧取得

Posted at

インストールされているパッケージの一覧取得

pythonで現在の環境でインストールされているパッケージの一覧が欲しい場合がある。
そのような場合にどうすれば良いかのまとめ。

コマンドライン

単に情報を知りたい場合には、コンソールで以下の様にすればすれば良い。

pip freeze
# .. output messages of command (example)
Jinja2==2.7.2
MarkupSafe==0.23
Pygments==1.6
Sphinx==1.2.2
docutils==0.11

プログラミング

何らかのコード上で例えばListとして出力したい場合。
pipのコードを読めば分かる。(参考になるのはpip/commands/freeze.py)

from pip.util import get_installed_distributions

skips = ['setuptools', 'pip', 'distribute', 'python', 'wsgiref']
for dist in get_installed_distributions(local_only=True, skip=skips):
    print(dist.project_name, dist.version)

""" output of script
docutils 0.11
Jinja2 2.7.2
MarkupSafe 0.23
Pygments 1.6
Sphinx 1.2.2
"""

pipにも依存したくない場合

pip/util.pyのなかを見てみる。

def get_installed_distributions(local_only=True,
                                skip=stdlib_pkgs,
                                include_editables=True,
                                editables_only=False):
    """
    Return a list of installed Distribution objects.

    If ``local_only`` is True (default), only return installations
    local to the current virtualenv, if in a virtualenv.

    ``skip`` argument is an iterable of lower-case project names to
    ignore; defaults to stdlib_pkgs

    If ``editables`` is False, don't report editables.

    If ``editables_only`` is True , only report editables.

    """
    if local_only:
        local_test = dist_is_local
    else:
        local_test = lambda d: True

    if include_editables:
        editable_test = lambda d: True
    else:
        editable_test = lambda d: not dist_is_editable(d)

    if editables_only:
        editables_only_test = lambda d: dist_is_editable(d)
    else:
        editables_only_test = lambda d: True

    return [d for d in pkg_resources.working_set
            if local_test(d)
            and d.key not in skip
            and editable_test(d)
            and editables_only_test(d)
            ]

結局、pkg_resources.working_setの中のオブジェクトを条件によって絞り込んでいるだけ。
なので、特に細かな絞り込みが必要ない場合にはpkg_resources.working_setを見れば良い。

import pkg_resources
for dist in pkg_resources.working_set:
    print(dist.project_name, dist.version)

#  output of script
"""
docutils 0.11
Jinja2 2.7.2
MarkupSafe 0.23
pip 1.4.1
Pygments 1.6
setuptools 0.9.8
Sphinx 1.2.2
"""
72
80
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
72
80