LoginSignup
7
6

More than 1 year has passed since last update.

pipとはなにか、何ができるか整理してみた【ゼロからPython勉強してみる】

Last updated at Posted at 2022-05-12

はじめに

前回は「コマンドプロンプトとpowershellの違いを整理するように。」と宿題を頂き、自分なりに整理した記事を投稿しましたが、今回は「pipについて整理するように。」と宿題を頂きましたので勉強してみた内容を整理してみます。

現在牛歩で進んでいる、ゼロから独学でPythonを勉強してみるシリーズの一環ですので超初心者が書いている備忘録であることをご理解下さい。

pip(ピップ)とは

pipとはPythonで開発されたパッケージを管理するパッケージマネージャです。
(pipの公式ページではパッケージインストーラーと書かれていますが、アンインストールやバージョンのチェックとかもできまるのでパッケージマネージャの方がしっくりくるかも。)
Pip Installs PackagesまたはPip Installs Pythonの略だと言われているようです。
pip自身もPythonのモジュールの一つと考えていいと思います。

pip is the package installer for Python. You can use it to install packages from the Python Package Index and other indexes.
引用 公式ページ:https://pip.pypa.io/en/stable/

pipPython公式のドキュメントによるとPython公式で推奨される標準的なパッケージマネージャであり、Python3においてはPython3.4以降ではPythonのインストール時に標準で一緒にpipもインストールされるようになっているようです。
そのおかげで私も特にpipのインストールを行わずpipの機能を使用できていました。

何ができるか

pipでできることは大まかに整理すると

  • ライブラリのインストール
  • ライブラリのアンインストール
  • ライブラリのアップデート
  • インストールされているライブラリの確認

などがあり、以下に書いてあるコマンドにオプションを使用することで様々なことができます。

参考

また、コマンドはpip helpで一覧を確認できるほか、pip help コマンドpip コマンド --helppip コマンド -hのどれでもで各コマンドのより詳しい説明を確認することができます。

> pip help

Usage:
  pip <command> [options]

Commands:
  install                     Install packages.
  download                    Download packages.
  uninstall                   Uninstall packages.
  freeze                      Output installed packages in requirements format.
  list                        List installed packages.
  show                        Show information about installed packages.
  check                       Verify installed packages have compatible dependencies.
  config                      Manage local and global configuration.
  search                      Search PyPI for packages.
  cache                       Inspect and manage pip's wheel cache.
  index                       Inspect information available from package indexes.
  wheel                       Build wheels from your requirements.
  hash                        Compute hashes of package archives.
  completion                  A helper command used for command completion.
  debug                       Show information useful for debugging.
  help                        Show help for commands.

General Options:
  -h, --help                  Show help.
  --debug                     Let unhandled exceptions propagate outside the main subroutine, instead of logging them to stderr.
  --isolated                  Run pip in an isolated mode, ignoring environment variables and user configuration.
  --require-virtualenv        Allow pip to only run in a virtual environment; exit with an error otherwise.
  -v, --verbose               Give more output. Option is additive, and can be used up to 3 times.
  -V, --version               Show version and exit.
  -q, --quiet                 Give less output. Option is additive, and can be used up to 3 times (corresponding to WARNING, ERROR, and CRITICAL logging levels).
  --log <path>                Path to a verbose appending log.
  --no-input                  Disable prompting for input.
  --proxy <proxy>             Specify a proxy in the form scheme://[user:passwd@]proxy.server:port.
  --retries <retries>         Maximum number of retries each connection should attempt (default 5 times).
  --timeout <sec>             Set the socket timeout (default 15 seconds).
  --exists-action <action>    Default action when a path already exists: (s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.
  --trusted-host <hostname>   Mark this host or host:port pair as trusted, even though it does not have valid or any HTTPS.
  --cert <path>               Path to PEM-encoded CA certificate bundle. If provided, overrides the default. See 'SSL Certificate Verification' in pip documentation for more information.
  --client-cert <path>        Path to SSL client certificate, a single file containing the private key and the certificate in PEM format.
  --cache-dir <dir>           Store the cache data in <dir>.
  --no-cache-dir              Disable the cache.
  --disable-pip-version-check
                              Don't periodically check PyPI to determine whether a new version of pip is available for download. Implied with --no-index.
  --no-color                  Suppress colored output.
  --no-python-version-warning
                              Silence deprecation warnings for upcoming unsupported Pythons.
  --use-feature <feature>     Enable new functionality, that may be backward incompatible.
  --use-deprecated <feature>  Enable deprecated functionality, that will be removed in the future.
> pip help install

Usage:
  pip install [options] <requirement specifier> [package-index-options] ...
  pip install [options] -r <requirements file> [package-index-options] ...
  pip install [options] [-e] <vcs project url> ...
  pip install [options] [-e] <local project path> ...
  pip install [options] <archive url/path> ...

Description:
  Install packages from:

  - PyPI (and other indexes) using requirement specifiers.
  - VCS project urls.
  - Local project directories.
  - Local or remote source archives.

  pip also supports installing from "requirements files", which provide
  an easy way to specify a whole environment to be installed.

Install Options:
  -r, --requirement <file>    Install from the given requirements file. This option can be used multiple times.
  -c, --constraint <file>     Constrain versions using the given constraints file. This option can be used multiple times.
  --no-deps                   Don't install package dependencies.
  --pre                       Include pre-release and development versions. By default, pip only finds stable versions.
  -e, --editable <path/url>   Install a project in editable mode (i.e. setuptools "develop mode") from a local project path or a VCS url.
  -t, --target <dir>          Install packages into <dir>. By default this will not replace existing files/folders in <dir>. Use --upgrade to replace existing packages in <dir> with new versions.
  --platform <platform>       Only use wheels compatible with <platform>. Defaults to the platform of the running system. Use this option multiple times to specify multiple platforms supported by the target interpreter.
  --python-version <python_version>
                              The Python interpreter version to use for wheel and "Requires-Python" compatibility checks. Defaults to a version derived from the running interpreter. The version can be specified using up to      
                              three dot-separated integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor version can also be given as a string without dots (e.g. "37" for 3.7.0).
  --implementation <implementation>
                              Only use wheels compatible with Python implementation <implementation>, e.g. 'pp', 'jy', 'cp',  or 'ip'. If not specified, then the current interpreter implementation is used.  Use 'py' to force    
                              implementation-agnostic wheels.
  --abi <abi>                 Only use wheels compatible with Python abi <abi>, e.g. 'pypy_41'. If not specified, then the current interpreter abi tag is used. Use this option multiple times to specify multiple abis supported   
                              by the target interpreter. Generally you will need to specify --implementation, --platform, and --python-version when using this option.
  --user                      Install to the Python user install directory for your platform. Typically ~/.local/, or %APPDATA%\Python on Windows. (See the Python documentation for site.USER_BASE for full details.)
  --root <dir>                Install everything relative to this alternate root directory.
  --prefix <dir>              Installation prefix where lib, bin and other top-level folders are placed
  --src <dir>                 Directory to check out editable projects into. The default in a virtualenv is "<venv path>/src". The default for global installs is "<current dir>/src".
  -U, --upgrade               Upgrade all specified packages to the newest available version. The handling of dependencies depends on the upgrade-strategy used.
  --upgrade-strategy <upgrade_strategy>
                              Determines how dependency upgrading should be handled [default: only-if-needed]. "eager" - dependencies are upgraded regardless of whether the currently installed version satisfies the
                              requirements of the upgraded package(s). "only-if-needed" -  are upgraded only when they do not satisfy the requirements of the upgraded package(s).
  --force-reinstall           Reinstall all packages even if they are already up-to-date.
  -I, --ignore-installed      Ignore the installed packages, overwriting them. This can break your system if the existing package is of a different version or was installed with a different package manager!
  --ignore-requires-python    Ignore the Requires-Python information.
  --no-build-isolation        Disable isolation when building a modern source distribution. Build dependencies specified by PEP 518 must be already installed if this option is used.
  --use-pep517                Use PEP 517 for building source distributions (use --no-use-pep517 to force legacy behaviour).
  --config-settings <settings>
                              Configuration settings to be passed to the PEP 517 build backend. Settings take the form KEY=VALUE. Use multiple --config-settings options to pass multiple keys to the backend.
  --install-option <options>  Extra arguments to be supplied to the setup.py install command (use like --install-option="--install-scripts=/usr/local/bin"). Use multiple --install-option options to pass multiple options to      
                              setup.py install. If you are using an option with a directory path, be sure to use absolute path.
  --global-option <options>   Extra global options to be supplied to the setup.py call before the install or bdist_wheel command.
  --compile                   Compile Python source files to bytecode
  --no-compile                Do not compile Python source files to bytecode
  --no-warn-script-location   Do not warn when installing scripts outside PATH
  --no-warn-conflicts         Do not warn about broken dependencies
  --no-binary <format_control>
                              Do not use binary packages. Can be supplied multiple times, and each time adds to the existing value. Accepts either ":all:" to disable all binary packages, ":none:" to empty the set (notice the    
                              colons), or one or more package names with commas between them (no colons). Note that some packages are tricky to compile and may fail to install when this option is used on them.
  --only-binary <format_control>
                              Do not use source packages. Can be supplied multiple times, and each time adds to the existing value. Accepts either ":all:" to disable all source packages, ":none:" to empty the set, or one or     
                              more package names with commas between them. Packages without binary distributions will fail to install when this option is used on them.
  --prefer-binary             Prefer older binary packages over newer source packages.
  --require-hashes            Require a hash to check each requirement against, for repeatable installs. This option is implied when any package in a requirements file has a --hash option.
  --progress-bar <progress_bar>
                              Specify whether the progress bar should be used [on, off] (default: on)
  --root-user-action <root_user_action>
                              Action if pip is run as a root user. By default, a warning message is shown.
  --no-clean                  Don't clean up build directories.

Package Index Options:
  -i, --index-url <url>       Base URL of the Python Package Index (default https://pypi.org/simple). This should point to a repository compliant with PEP 503 (the simple repository API) or a local directory laid out in the     
                              same format.
  --extra-index-url <url>     Extra URLs of package indexes to use in addition to --index-url. Should follow the same rules as --index-url.
  --no-index                  Ignore package index (only looking at --find-links URLs instead).
  -f, --find-links <url>      If a URL or path to an html file, then parse for links to archives such as sdist (.tar.gz) or wheel (.whl) files. If a local path or file:// URL that's a directory, then look for archives in the    
                              directory listing. Links to VCS project URLs are not supported.

General Options:
  -h, --help                  Show help.
  --debug                     Let unhandled exceptions propagate outside the main subroutine, instead of logging them to stderr.
  --isolated                  Run pip in an isolated mode, ignoring environment variables and user configuration.
  --require-virtualenv        Allow pip to only run in a virtual environment; exit with an error otherwise.
  -v, --verbose               Give more output. Option is additive, and can be used up to 3 times.
  -V, --version               Show version and exit.
  -q, --quiet                 Give less output. Option is additive, and can be used up to 3 times (corresponding to WARNING, ERROR, and CRITICAL logging levels).
  --log <path>                Path to a verbose appending log.
  --no-input                  Disable prompting for input.
  --proxy <proxy>             Specify a proxy in the form scheme://[user:passwd@]proxy.server:port.
  --retries <retries>         Maximum number of retries each connection should attempt (default 5 times).
  --timeout <sec>             Set the socket timeout (default 15 seconds).
  --exists-action <action>    Default action when a path already exists: (s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.
  --trusted-host <hostname>   Mark this host or host:port pair as trusted, even though it does not have valid or any HTTPS.
  --cert <path>               Path to PEM-encoded CA certificate bundle. If provided, overrides the default. See 'SSL Certificate Verification' in pip documentation for more information.
  --client-cert <path>        Path to SSL client certificate, a single file containing the private key and the certificate in PEM format.
  --cache-dir <dir>           Store the cache data in <dir>.
  --no-cache-dir              Disable the cache.
  --disable-pip-version-check
                              Don't periodically check PyPI to determine whether a new version of pip is available for download. Implied with --no-index.
  --no-color                  Suppress colored output.
  --no-python-version-warning
                              Silence deprecation warnings for upcoming unsupported Pythons.
  --use-feature <feature>     Enable new functionality, that may be backward incompatible.
  --use-deprecated <feature>  Enable deprecated functionality, that will be removed in the future.

install ライブラリのインストール

Pythonはインストールした際にすでに組み込まれているライブラリがあり、それらを標準ライブラリといいます。
それ以外の後からPythonに各自が追加するライブラリを外部ライブラリといい、それらの多くはPyPI(Python Package Index)というPython用ソフトウェアのリポジトリに登録されており、容易に検索可能であるほか、pipを用いてインターネット経由でインストールすることが可能のようです。

外部ライブラリの入手先としてPyPIを挙げましたが、pipはPyPI以外のリポジトリやローカルのファイルからもライブラリのインストールを行えるとのことです。

Install packages from:

  • PyPI (and other indexes) using requirement specifiers.
  • VCS project urls.
  • Local project directories.
  • Local or remote source archives.

pip also supports installing from “requirements files”, which provide an easy way to specify a whole environment to be installed.
引用:https://pip.pypa.io/en/stable/cli/pip_install/

標準のインストール

特にライブラリのバージョンやインストールするディレクトリを設定せず、PyPIに登録されているライブラリをインストールする場合は、以下のコマンドをコンソールに入力し実行することで最新版のライブラリをインストールできます。

pip install ライブラリ 

オプション、引数

pipを用いてライブラリをインストールする際は各種オプションを用いることにより様々なインストール方法を指定できます。
コマンドは以下の形式で記載します。([ ]の内容は省略可能です。)

pip install [オプション] <ライブラリ名> [バージョン指定子] [パッケージインデックスオプション]
pip install [オプション] -r <requirementsファイル> [パッケージインデックスオプション]
pip install [オプション] [-e] <VSCプロジェクトのURL>
pip install [オプション] [-e] <ローカルプロジェクトのURL>
pip install [オプション] <アーカイブのURLまたはパス>

オプションにはinstallコマンド以外でも使えるGeneral Optionsinstallコマンド用のInstall Optionsがあるようです。
非常に種類が多いので、helpコマンドで表示されるオプションと説明の一覧は下に記しますが、整理するのは一部にとどめます。

General Options
オプション 説明
-h, --help Show help.
ヘルプを表示する。
--debug Let unhandled exceptions propagate outside the main subroutine, instead of logging them to stderr.
--isolated Run pip in an isolated mode, ignoring environment variables and user configuration.
--require-virtualenv Allow pip to only run in a virtual environment; exit with an error otherwise.
-v, --verbose Give more output. Option is additive, and can be used up to 3 times.
-V, --version Show version and exit.
-q, --quiet Give less output. Option is additive, and can be used up to 3 times (corresponding to WARNING, ERROR, and CRITICAL logging levels).
--log Path to a verbose appending log.
--no-input Disable prompting for input.
--proxy Specify a proxy in the form [user:passwd@]proxy.server:port.
--retries Maximum number of retries each connection should attempt (default 5 times).
--timeout Set the socket timeout (default 15 seconds).
--exists-action Default action when a path already exists: (s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.
--trusted-host Mark this host or host:port pair as trusted, even though it does not have valid or any HTTPS.
--cert Path to PEM-encoded CA certificate bundle. If provided, overrides the default. See 'SSL Certificate Verification' in pip documentation for more information.
--client-cert Path to SSL client certificate, a single file containing the private key and the certificate in PEM format.
--cache-dir Store the cache data in .
--no-cache-dir Disable the cache.
--disable-pip-version-check Don't periodically check PyPI to determine whether a new version of pip is available for download. Implied with --no-index.
--no-color Suppress colored output.
--no-python-version-warning Silence deprecation warnings for upcoming unsupported Pythons.
--use-feature Enable new functionality, that may be backward incompatible.
--use-deprecated Enable deprecated functionality, that will be removed in the future.
Install Options
オプション 説明
-r, --requirement Install from the given requirements file. This option can be used multiple times.
指定された要件ファイルの記述を参照してインストールする。
-c, --constraint Constrain versions using the given constraints file. This option can be used multiple times.
指定された制約ファイルの記述を参照してバージョンを管理する。
--no-deps Don't install package dependencies.
依存関係にある他のライブラリをインストールしない(-U,-upgradeと併用すると指定したライブラリのみアップグレードしてくれる)
--pre Include pre-release and development versions. By default, pip only finds stable versions.
インストール対象のバージョンにプレリリースバージョンと開発バージョンを含める。デフォルト(--preオプションを使用しなければ)ではインストール対象は安定したバージョンのみとなる。
-e, --editable Install a project in editable mode (i.e. setuptools "develop mode") from a local project path or a VCS url.
-t, --target Install packages into . By default this will not replace existing files/folders in . Use --upgrade to replace existing packages in with new versions.
ライブラリを任意のディレクトリにインストールする。デフォルトで任意のディレクトリに存在するファイルの上書きは行われないが、--upgrageオプションを使用して新しいバージョンに置き換えることができる。
--platform Only use wheels compatible with . Defaults to the platform of the running system. Use this option multiple times to specify multiple platforms supported by the target interpreter.
--python-version The Python interpreter version to use for wheel and "Requires-Python" compatibility checks. Defaults to a version derived from the running interpreter. The version can be specified using up to three dot-separated integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor version can also be given as a string without dots (e.g. "37" for 3.7.0).
--implementation Only use wheels compatible with Python implementation , e.g. 'pp', 'jy', 'cp', or 'ip'. If not specified, then the current interpreter implementation is used. Use 'py' to force implementation-agnostic wheels.
--abi Only use wheels compatible with Python abi , e.g. 'pypy_41'. If not specified, then the current interpreter abi tag is used. Use this option multiple times to specify multiple abis supported by the target interpreter. Generally you will need to specify --implementation, --platform, and --python-version when using this option.
--user Install to the Python user install directory for your platform. Typically ~/.local/, or %APPDATA%\Python on Windows. (See the Python documentation for site.USER_BASE for full details.)
--root Install everything relative to this alternate root directory.
--prefix Installation prefix where lib, bin and other top-level folders are placed.
--src Directory to check out editable projects into. The default in a virtualenv is "/src". The default for global installs is "/src".
-U, --upgrade Upgrade all specified packages to the newest available version. The handling of dependencies depends on the upgrade-strategy used.
指定されたパッケージ(ライブラリ)を利用可能な最新バージョンにアップグレードする。
--upgrade-strategy Determines how dependency upgrading should be handled [default: only-if-needed]. "eager" - dependencies are upgraded regardless of whether the currently installed version satisfies the requirements of the upgraded package(s). "only-if-needed" - are upgraded only when they do not satisfy the requirements of the upgraded package(s).
ライブラリをアップグレードする際に、依存関係にあるパッケージもアップグレードするかを選択できる。
eagerを選択した場合、動作要件の適否にかかわらず依存関係にあるパッケージすべてをアップグレードする。
only-if-neededを選択した場合、動作要件を満たさない場合にのみ動作要件を満たすように依存関係にあるパッケージをアップグレードする。(デフォルトではonly-if-neededに設定されている)
--force-reinstall Reinstall all packages even if they are already up-to-date.<現在のバージョンが最新であるか否かに関わらず、パッケージを再インストールする>
-I, --ignore-installed Ignore the installed packages, overwriting them. This can break your system if the existing package is of a different version or was installed with a different package manager!
--ignore-requires-python Ignore the Requires-Python information.
--no-build-isolation Disable isolation when building a modern source distribution. Build dependencies specified by PEP 518 must be already installed if this option is used.
--use-pep517 Use PEP 517 for building source distributions (use --no-use-pep517 to force legacy behaviour).
--install-option Extra arguments to be supplied to the setup.py install command (use like --install-option="--install-scripts=/usr/local/bin"). Use multiple --install-option options to pass multiple options to setup.py install. If you are using an option with a directory path, be sure to use absolute path.
--global-option Extra global options to be supplied to the setup.py call before the install or bdist_wheel command.
--compile Compile Python source files to bytecode
--no-compile Do not compile Python source files to bytecode
--no-warn-script-location Do not warn when installing scripts outside PATH
--no-warn-conflicts Do not warn about broken dependencies
--no-binary Do not use binary packages. Can be supplied multiple times, and each time adds to the existing value. Accepts either ":all:" to disable all binary packages, ":none:" to empty the set (notice the colons), or one or more package names with commas between them (no colons). Note that some packages are tricky to compile and may fail to install when this option is used on them.
--only-binary Do not use source packages. Can be supplied multiple times, and each time adds to the existing value. Accepts either ":all:" to disable all source packages, ":none:" to empty the set, or one or more package names with commas between them. Packages without binary distributions will fail to install when this option is used on them.
--prefer-binary Prefer older binary packages over newer source packages.
--require-hashes Require a hash to check each requirement against, for repeatable installs. This option is implied when any package in a requirements file has a --hash option.
--progress-bar Specify type of progress to be displayed [off
--no-clean Don't clean up build directories.

パッケージインデックスオプションでは、pipを用いてライブラリをインストールする際に見に行くURL(デフォルトでは https://pypi.org/simple )の指定等が行えるようですが、ここに関してはまだ理解ができていないのと当面PyPI以外からパッケージをインストールする予定もないので、今後必要になったら再度整理します。

ライブラリのバージョンを指定してインストールする

インストールの際にはバージョン指定子(Version specifiers)を使ってライブラリのバージョンを指定することができます。

参考

バージョン指定子には==~=>=<=><などがあります。
これらは,を使ってANDで条件を組み合わせることも可能です。(例:hoge>=1.0,<=3.3 はバージョン1.0以上3.3以下のhogeを指定している)

  • Version matching :一致するバージョンを指定
    ==バージョンで指定、指定されたバージョンと一致したバージョンをインストールする。
    *でワイルドカード表現を使うことも可能。ワイルドカードを使用しないでの==の使用は推奨されていないもよう。
pip install hoge==1.1.0
#hogeのバージョン1.1.0をインストール

pip install hoge==1.1.*
# hogeのバージョン1.1の中で最新のものをインストールする。
# hogeのバージョンに1.0.0、1.1.0、1.1.1、1.2.0があった場合インストールされるのは1.1.1
  • 存在しないバージョンを指定するとエラー文とともにインストールできるバージョンの一覧が表示される。
  • ==1.22のようにパッチバージョンを無視して指定した場合0が補足されて==1.22.0が指定されるようです。
    pipとは_03.png
  • Version exclusion:特定バージョンの除外
    !=バージョンで指定したバージョンをインストールする候補から除外する。

  • Inclusive ordered comparison:特定バージョン以上(または以下)を指定
    >=バージョンで特定バージョン以上、<=バージョンで特定バージョン以下を指定できる、その範囲内で最新のものがインストールされる。

  • Exclusive ordered comparison:特定バージョンより大きい(または未満)を指定
    >バージョンで特定バージョンより大きいバージョン、<=バージョンで特定バージョンより小さいバージョンを指定できる、その範囲内で最新のものがインストールされる。

  • Compatible release:互換性のあるものから指定
    ~= バージョンで指定、互換性があるものの中で最新のバージョンをインストールする。

例としてインストールしたいhogeというライブラリに0.1.00.2.00.2.10.2.20.3.0というバージョンがあった時、以下のコマンドを実行すると0.2.2がインストールされる。

pip install hoge~=0.2.0

なお、上記のコマンドと以下のコマンドは同義となる。

pip install hoge>=0.2.0,==0.2.* 
  • Arbitrary equality:任意の文字列に対する一致?
    ===バージョンでもインストールしたいバージョンを指定できるようでしたが、このバージョン指定子は解説を読んでもいまいち理解ができませんでした。
    標準のバージョンを表すフォーマット[N!]N(.N)*[{a|b|rc}N][.postN][.devN]以外のフォーマットで管理されているライブラリのバージョンを指定できる指定子のようですが、使用は非推奨とのことなのでこの程度の認識で終わらせておきます。例えば、hogeというライブラリにfoobarというバージョンがあった場合pip install hoge===foobarfoobarというバージョンのhogeをインストールできるらしい。

The canonical public version identifiers MUST comply with the following scheme:
[N!]N(.N)*[{a|b|rc}N][.postN][.devN]
Public version identifiers are separated into up to five segments:

  • Epoch segment: N!
  • Release segment: N(.N)*
  • Pre-release segment: {a|b|rc}N
  • Post-release segment: .postN
  • Development release segment: .devN

引用:https://peps.python.org/pep-0440/#public-version-identifiers

environment markersを用いてインストールの条件を指定する

使用するPythonのバージョンやOSによってインストールするかしないかを設定できるらしい。
条件を指定するには先ほどのバージョン指定子のようにライブラリ名の後ろに記述を追加する。
以下に示すsys_platform等がenvironment markerというらしい。

#OSがWindows32bitならhogeをインストールする
pip install hoge;sys_platform == win32

#OSがWindows32bitならhogeをインストールしない
pip install hoge;sys_platform!=win32

#Pythonのバージョンが3.9以下ならhogeをインストールする
pip install hoge;python_version<'3.9'

参考

複数のライブラリを一括でインストールする

ライブラリ名やバージョンを記載したテキストファイルである要件ファイル(requirementsファイル)を使用することで、複数のライブラリを指定したバージョンでまとめてインストールすることが可能です。
この方法は使用している環境のライブラリ構成を要件ファイルとして出力し、他の環境で同様のライブラリ構成を構築したい際などに使用します。
要件ファイルは一般的にrequirements.txtという名前で作成するようですが、ファイルの名前は任意のもので構いません。
以下のどちらかのコマンドで要件ファイルに記載されたパッケージをインストールします。

-r 要件ファイルのパス
--requirement 要件ファイルのパス

要件ファイルのフォーマットについては以下に示す例のように、各行にライブラリの名前とそのライブラリインストール時のオプション等を記載する形です。(hogeはインストールしたいライブラリ名)
installコマンドでインストールする際のinstall以下の引数等の部分を各行に記載するという認識で問題ないと思います。
また、指定した要件ファイル内で他の要件ファイルを指定することでそれに記載されたライブラリのインストールも可能です。

requirements.txt

##Pythonのコード同様に#以下はコメントとなる。

##バージョン指定なしでライブラリ名のみで最新版をインストール
hoge

##バージョン指定をしてインストール
hoge~=3.5.0
hoge==1.22.3
hoge>=1.2.0,==1.2.*

##環境の条件を指定してインストール

###Pythonのバージョンが3.8より小さければhogeのバージョン1.2.0をインストール
hoge==1.2.0;python_version<'3.8' 

###使用環境がWindowsの32bitの場合hogeをインストール
hoge; sys_platform == 'win32'

##他の要件ファイルを参照してインストール(ファイル名は任意)
-r piyo.txt
--requirement piyopiyo.txt

##ローカル、インターネット上のファイルを使用してインストール
###ファイルのディレクトリまたはURLを記載
C:\Users\user\Downloads\hoge.whl
http://piyo/hoge.whl

要件ファイルの詳しい解説や使用できるオプションについては以下を参照

ライブラリのアップグレード

すでにインストールしているライブラリについて、-Uまたは--upgradeのオプションを使用することで最新のバージョンにアップグレードすることができます。
また、--upgrade-strategy <アップグレード方法>ライブラリをアップグレードする際に、依存関係にある他のライブラリを必要の有無に応じてアップグレードすることもできます。

オプション 説明
-U, --upgrade Upgrade all specified packages to the newest available version. The handling of dependencies depends on the upgrade-strategy used.
指定されたパッケージ(ライブラリ)を利用可能な最新バージョンにアップグレードする。
--upgrade-strategy Determines how dependency upgrading should be handled [default: only-if-needed]. "eager" - dependencies are upgraded regardless of whether the currently installed version satisfies the requirements of the upgraded package(s). "only-if-needed" - are upgraded only when they do not satisfy the requirements of the upgraded package(s).
ライブラリをアップグレードする際に、依存関係にあるパッケージもアップグレードするかを選択できる。
eagerを選択した場合、動作要件の適否にかかわらず依存関係にあるパッケージすべてをアップグレードする。
only-if-neededを選択した場合、動作要件を満たさない場合にのみ動作要件を満たすように依存関係にあるパッケージをアップグレードする。(デフォルトではonly-if-neededに設定されている)
#hogeに加えhogeと依存関係にあるもののうちアップグレードが必要なもののみアップグレードする。
pip install -U hoge
pip install -U --upgrade-strategy only-if-needed hoge

#hogeに加えhogeと依存関係にあるものすべてアップグレードする。
pip install -U --upgrade-strategy eager hoge

古いライブラリがインストールされている状態でpip install hogeを試すと、既に古いバージョンがインストールされていると言われて最新バージョンのインストールはできなかったが、pip install hoge==バージョンで最新バージョンを指定してみたところ古いバージョンはアンインストールされ指定したバージョンを無事インストールできた。
この方法でアップグレードすることも可能のようですが、依存関係にあるものがどうなるかは未検証。
黙ってオプションを使った方が早いかもしれない。
pipとは_04.png

uninstall ライブラリのアンインストール

先ほどまではインストールの方法で今度はアンインストールについて。

標準的なアンインストール

オプションを設定しないでただ指定したライブラリをアンインストールしたい場合は以下のコマンドで実行できる。

pip uninstall ライブラリ名

pipとは_05.png

オプション

uninstallコマンドでは先述したGeneral Optionsに加えてUninstall Optionsが使用できます。

Install Options
オプション 説明
-r, --requirement Uninstall all the packages listed in the given requirements file. This option can be used multiple times.
要件ファイルに記載されたライブラリすべてをアンインストールできる。
-y, --yes Don't ask for confirmation of uninstall deletions.
アンインストール時の確認をなくせる。

オプションを指定する際のコマンドの記述は以下の通り

pip uninstall [オプション] ライブラリ名
pip uninstall [オプション] -r 要件ファイルのパス

要件ファイルを用いて一括アンインストール

-rまたは--requirementコマンドにより要件ファイルを読み込んで、installコマンドの時と同様に複数のライブラリをまとめてアンインストールすることが可能です。


#要件ファイルがカレントディレクトリにあればファイル名のみでよい
#大量のライブラリをアンインストールする際はライブラリ毎に実行の確認をされて面倒
pip uninstall -r 要件ファイルのパス
pip uninstall --requirement 要件ファイルのパス

#なので`-y`または`--yes`オプションを併用することをおすすめします
pip uninstall -y -r 要件ファイルのパス
pip uninstall --yes --requirement 要件ファイルのパス

依存関係にあるライブラリのアンインストール

pipを使ったインストールやアップグレードではライブラリを一つインストールするだけで依存関係にあるライブラリも一緒にインストールしてくれたりアップグレードしてくれてとても便利です。
ただし、pipの標準機能でのアンインストール時には依存関係にあるライブラリのアンインストールまではやってくれません。

ですが、以下の記事によるとpip-autoremoveというライブラリをインストールすれば依存関係にあるパッケージを丸ごとアンインストールしてくれるとのことです。

インストールしても動かなかった場合

私の環境(OS:Windows、pip-autoremoveはver.0.10.0)ではどうも素直に対応しませんでした。
pip install pip-autoremoveでインストールしてpip-autoremove ライブラリ名でアンインストールをしてくれるとのことなのですが、インストールして実行してみても以下のようなエラーが表示されます。

Traceback (most recent call last):
  File "C:\Users\ユーザー名\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_maindule_as_main
    return _run_code(code, main_globals, None,
  File "C:\Users\ユーザー名\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\WorkSpace\Python\venv\piptest\Scripts\pip-autoremove.exe\__main__.py", line 4, in <module>
ModuleNotFoundError: No module named `pip_autoremove`

詳しくはわかりませんが'pip_autoremove'ってモジュールがないと文句を言っているようです。
同様の症状を探してみたら以下のページで解決方法を見つけました。どうやらWindows特有の症状みたいでした。

解決方法としては、pipでpip-autoremoveをインストールする際にpip_autoremove.pyというモジュールがPythonのインストールフォルダまたは仮想環境のフォルダの\Scriptsに追加されるのですが、このモジュールを\Lib\site-packagesに移動して、コマンドもpython -m pip_autoremove ライブラリ名("-"ではなく"_"であることに注意)で実行すれば動くとのこと。

pipとは_06.png

コマンドについてはpip_autoremove.pyがちゃんと\Lib\site-packagesに入っていて\ScriptsにPATHが通っていればpip-autoremove ライブラリ名でも動作することを確認した。なので以下のどっちでもよい。

##モジュールがpip_autoremove.pyなので"_"であることに注意
python -m pip_autoremove ライブラリ名

##pip-autoremove.exeを呼び出すときは"-"であることに注意
pip-autoremove ライブラリ名

pipとは_07.png

余談

無事pip-autoremoveは動くようになり、大体問題なく使えたのですが試しに依存関係のパッケージが多いJupyterをインストールしてみてpip-autoremoveで依存関係ごとアンインストールを試みたところ以下のようなエラーが発生しました。
PermissionError: [WinError 5] アクセスが拒否されました。とありますが、管理者権限で実行していました。
同じような症状が出ているひともいましたが、私が見たときはこのスレッドでは解決策は出ていませんでした。(https://github.com/invl/pip-autoremove/issues/48)

(piptest) PS C:\WorkSpace\Python\Practice> python -m pip_autoremove jupyter 

#~省略~

Uninstall (y/N)? y

#~省略~

Found existing installation: pywin32 304
  Successfully uninstalled pywin32-304 
ERROR: Exception:
Traceback (most recent call last):
  File "C:\WorkSpace\Python\venv\piptest\lib\site-packages\pip\_internal\cli\base_command.py", line 167, in exc_logging_wrapper
    status = run_func(*args)
  File "C:\WorkSpace\Python\venv\piptest\lib\site-packages\pip\_internal\commands\uninstall.py", line 102, in run
    uninstall_pathset.commit()
  File "C:\WorkSpace\Python\venv\piptest\lib\site-packages\pip\_internal\req\req_uninstall.py", line 420, in commit
    self._moved_paths.commit()
  File "C:\WorkSpace\Python\venv\piptest\lib\site-packages\pip\_internal\req\req_uninstall.py", line 273, in commit
    save_dir.cleanup()
  File "C:\WorkSpace\Python\venv\piptest\lib\site-packages\pip\_internal\utils\temp_dir.py", line 173, in cleanup
    rmtree(self._path)
  File "C:\WorkSpace\Python\venv\piptest\lib\site-packages\pip\_vendor\tenacity\__init__.py", line 326, in wrapped_f
    return self(f, *args, **kw)
  File "C:\WorkSpace\Python\venv\piptest\lib\site-packages\pip\_vendor\tenacity\__init__.py", line 406, in __call__
    do = self.iter(retry_state=retry_state)
  File "C:\WorkSpace\Python\venv\piptest\lib\site-packages\pip\_vendor\tenacity\__init__.py", line 362, in iter
    raise retry_exc.reraise()
  File "C:\WorkSpace\Python\venv\piptest\lib\site-packages\pip\_vendor\tenacity\__init__.py", line 195, in reraise
    raise self.last_attempt.result()
  File "C:\Users\ユーザー名\AppData\Local\Programs\Python\Python310\lib\concurrent\futures\_base.py", line 439, in result
    return self.__get_result()
  File "C:\Users\ユーザー名\AppData\Local\Programs\Python\Python310\lib\concurrent\futures\_base.py", line 391, in __get_result
    raise self._exception
  File "C:\WorkSpace\Python\venv\piptest\lib\site-packages\pip\_vendor\tenacity\__init__.py", line 409, in __call__
    result = fn(*args, **kwargs)
  File "C:\WorkSpace\Python\venv\piptest\lib\site-packages\pip\_internal\utils\misc.py", line 124, in rmtree
    shutil.rmtree(dir, ignore_errors=ignore_errors, onerror=rmtree_errorhandler)
  File "C:\Users\ユーザー名\AppData\Local\Programs\Python\Python310\lib\shutil.py", line 747, in rmtree
    return _rmtree_unsafe(path, onerror)
  File "C:\Users\ユーザー名\AppData\Local\Programs\Python\Python310\lib\shutil.py", line 617, in _rmtree_unsafe
    onerror(os.unlink, fullname, sys.exc_info())
  File "C:\Users\ユーザー名\AppData\Local\Programs\Python\Python310\lib\shutil.py", line 615, in _rmtree_unsafe
    os.unlink(fullname)
PermissionError: [WinError 5] アクセスが拒否されました。: 'C:\\WorkSpace\\Python\\venv\\piptest\\Lib\\site-packages\\~1win32_system32\\pythoncom310.dll'
Traceback (most recent call last):
  File "C:\Users\ユーザー名\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Users\ユーザー名\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\WorkSpace\Python\venv\piptest\lib\site-packages\pip_autoremove.py", line 214, in <module>
    main()
  File "C:\WorkSpace\Python\venv\piptest\lib\site-packages\pip_autoremove.py", line 158, in main
    autoremove(args, yes=opts.yes)
  File "C:\WorkSpace\Python\venv\piptest\lib\site-packages\pip_autoremove.py", line 45, in autoremove
    remove_dists(dead)
  File "C:\WorkSpace\Python\venv\piptest\lib\site-packages\pip_autoremove.py", line 121, in remove_dists
    subprocess.check_call(pip_cmd + ["uninstall", "-y"] + [d.project_name for d in dists])
  File "C:\Users\ユーザー名\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 369, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['C:\\WorkSpace\\Python\\venv\\piptest\\Scripts\\python.exe', '-m', 'pip', 'uninstall', '-y', 'jupyter-core', 'traitlets', 'nbclient', 'webencodings', 'jupyterlab-widgets', 'bleach', 'Jinja2', 'decorator', 'nbformat', 'terminado', 'argon2-cffi-bindings', 'jsonschema', 'stack-data', 'fastjsonschema', 'nbconvert', 'pycparser', 'jupyter-console', 'ipython-genutils', 'six', 'python-dateutil', 'jedi', 'jupyterlab-pygments', 'parso', 'cffi', 'colorama', 'backcall', 'MarkupSafe', 'ipython', 'pickleshare', 'pywin32', 'jupyter', 'notebook', 'prometheus-client', 'mistune', 'jupyter-client', 'ipywidgets', 'widgetsnbextension', 'Send2Trash', 'tornado', 'nest-asyncio', 'pure-eval', 'psutil', 'pyzmq', 'argon2-cffi', 'soupsieve', 'pyrsistent', 'executing', 'entrypoints', 'debugpy', 'tinycss2', 'prompt-toolkit', 'matplotlib-inline', 'packaging', 'QtPy', 'pywinpty', 'qtconsole', 'wcwidth', 'defusedxml', 'pyparsing', 'asttokens', 'Pygments', 'beautifulsoup4', 'ipykernel', 'pandocfilters', 'attrs']' returned non-zero exit status 2.

何度かjupyterの再インストールとアンインストールを繰り返していたところ、このエラーは毎回、pywin32のアンインストールが成功し、次のパッケージのアンインストールに進むと発生していることがわかりました。

詳しいことはてんでわからないのですが、pywin32が何かしら影響しているのであればという先にアンインストールしてしまえということで、jupyterインストール後pip uninstall pywin32でpywin32のみアンインストール後にpip-autoremove jupyterを実行したところエラーは出ずしっかりと依存関係のパッケージもアンインストールされていました。

ちなみにrequirements.txtにjupyterと依存関係諸々のパッケージを記載してpip uninstall -r -y requirements.txtでアンインストールしてみたところエラーが出なかったです。やってることは同じようなことに感じるのですがpip-autoremoveでだけエラーがなぜ出るのかは私の頭ではさっぱり不明。

根本的な解決には至っていませんがこんなことあったよということで書いておきました。

list インストールされているライブラリを表示する

listコマンドを使って、現在インストールされているライブラリの一覧を表示することができます。
並び順はライブラリ名でソートされているようです。

標準的な一覧表示

以下のコマンドでインストールされているライブラリ(パッケージ)とそのバージョンを表示します。

pip list
> pip list
Package        Version
-------------- -------
Click          7.0
colorama       0.4.4
Flask          2.1.2
itsdangerous   2.1.2
Jinja2         3.1.2
MarkupSafe     2.1.1
numpy          1.22.3
pip            22.0.4
pip-autoremove 0.10.0
pipdeptree     2.2.1
setuptools     62.1.0
Werkzeug       2.1.2

オプション

listコマンドではGeneral Optionsに加えてList Optionsが使用できます。
オプションによってリスト化するライブラリの対象を選択したり表示形式を変えられます。

Install Options
オプション 説明
-o, --outdated List outdated packages
バージョンが最新ではないライブラリのリストを表示する。
-u, --uptodate List uptodate packages
バージョンが最新であるライブラリのリストを表示する。
-e, --editable List editable projects.
編集可能であるライブラリのリストを表示する。
-l, --local If in a virtualenv that has global access, do not list globally-installed packages.
仮想環境がグローバル環境に存在する場合、グローバル環境にインストールされたライブラリを表示しない?
--user Only output packages installed in user-site.
ユーザーディレクトリにインストールされたライブラリのリストを表示する。(pip install --user hogeでインストールされたやつら)
--path Restrict to the specified installation path for listing packages (can be used multiple times).
指定されたフォルダにインストールされたライブラリのリストを表示する?
--pre Include pre-release and development versions. By default, pip only finds stable versions.
リストにプレリリースバージョンも含めて表示する。
--format Select the output format among: columns (default), freeze, or json
出力のフォーマットをcolumsfreezejsonから指定できる。デフォルトはcolumns
--not-required List packages that are not dependencies of installed packages.
他のライブラリに依存されていないライブラリのリストを表示する。
--exclude-editable Exclude editable package from output.
編集可能なライブラリをリストから除く。
--include-editable Include editable package from output.
編集可能なライブラリをリストに含める。
--exclude Exclude specified package from the output
指定したライブラリをリストから除外する。

オプションを指定する際の記述は以下

pip list [オプション]
##プレリリースバージョンを含めてバージョンが最新ではないライブラリ一覧を表示
> pip list -o --pre
Package    Version Latest Type
---------- ------- ------ -----
Click      7.0     8.1.3  wheel
pip        22.0.4  22.1   wheel
setuptools 62.1.0  62.2.0 wheel

show ライブラリの情報を表示する

showコマンドを使用してインストールしたライブラリに関する情報を表示することができます。

標準的な情報表示

以下のコマンドで指定したライブラリの情報を確認できます。

pip show ライブラリ名
> pip show flask
Name: Flask
Version: 2.1.2
Summary: A simple framework for building complex web applications.
Home-page: https://palletsprojects.com/p/flask
Author: Armin Ronacher
Author-email: armin.ronacher@active-4.com
License: BSD-3-Clause
Location: c:\workspace\python\venv\piptest\lib\site-packages
Requires: click, itsdangerous, Jinja2, Werkzeug
Required-by:

オプション

showコマンドではGeneral Optionsに加えてShow Optionsが使用できます。

Show Options
オプション 説明
-f, --files Show the full list of installed files for each package.ライブラリに含まれているファイル全てをリストで表示する。

オプションを指定する際の記述は以下

pip show [オプション] ライブラリ名

freeze インストールされたライブラリを要件ファイルのフォーマットで出力する

freezeコマンドを使うとインストールされているライブラリの一覧をinstalluninstallコマンドの-rオプションで読み込む要件ファイル(requirements.txt)のフォーマットで出力できます。
このコマンドを使うことで自分のライブラリ環境を他人が楽に再現できます。

標準的な出力

以下のコマンドで一覧を出力できます。

pip freeze
> pip freeze
Click==7.0
colorama==0.4.4
Flask==2.1.2
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.1
numpy==1.22.3
pip-autoremove==0.10.0
pipdeptree==2.2.1
Werkzeug==2.1.2

pip list --format=freezeでもfreeze同様のフォーマットで出力できるが、freezeで出力されるリストと異なりpip、setuptools等のパッケージ管理ツールも含まれるらしい。

> pip list --format=freeze
Click==7.0
colorama==0.4.4
Flask==2.1.2
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.1
numpy==1.22.3
pip==22.0.4
pip-autoremove==0.10.0
pipdeptree==2.2.1
setuptools==62.1.0
Werkzeug==2.1.2

出力内容をテキストデータに出力する際はコマンドの後ろに> [テキストファイル]を付ければよい。
これはpipやPythonの機能ではなく、コマンドプロンプトやpowershellの機能なので[コマンド] < [テキストファイル]でfreezeに限らずコマンドの内容をテキストに出力できるらしい。

pip ferrze > requirements.txt

pip ferrze > C:\WorkSpace\requirements.txt

参考

オプション

showコマンドではGeneral Optionsに加えてShow Optionsが使用できます。

Show Options
オプション 説明
-r, --requirement Use the order in the given requirements file and its comments when generating output. This option can be used multiple times.要件ファイルの内容に従ってリストを出力する?
-l, --local If in a virtualenv that has global access, do not output globally-installed packages.
仮想環境がグローバル環境に存在する場合、グローバル環境にインストールされたライブラリを表示しない?
--user Only output packages installed in user-site.
ユーザーディレクトリにインストールされたライブラリのリストを表示する。(pip install --user hogeでインストールされたやつら)
--path Restrict to the specified installation path for listing packages (can be used multiple times).
指定されたフォルダにインストールされたライブラリのリストを表示する?
--all Do not skip these packages in the output: setuptools, wheel, distribute, pip
setuptools、 wheel、distribute、pipなどのパッケージ管理ツールも含んでリストを表示する。(pip list --format=freezeと同じ結果になると予想)
--exclude-editable Exclude editable package from output.
編集可能なライブラリをリストから除く。
--exclude Exclude specified package from the output
指定したライブラリをリストから除外する。

オプションを指定する際の記述は以下

pip freeze [オプション]

check 依存関係の状態をチェックする

checkコマンドを使ってインストールしているライブラリの依存関係に問題がないか確認することができます。

標準の状態確認

以下のコマンドで確認できます。

pip check
##依存関係に問題がない場合
> pip check
No broken requirements found.

##動作要件のライブラリがインストールされていない場合
##flaskのバージョン2.1.2にはclickが必要だがインストールされていない
> pip check
flask 2.1.2 requires click, which is not installed.

##動作要件のライブラリのバージョンが要件を満たしていない場合
##flaskのバージョン2.1.2にはclickのバージョン8.0以上が必要だがインストールされているバージョンが7.0
> pip check
flask 2.1.2 has requirement click>=8.0, but you have click 7.0.

特定のライブラリの依存関係はpipdeptreeというパッケージを使うとツリー形式で確認できる。

##pipdeptreeのインストール
>pip install pipdeptree

## flaskの依存関係を要求バージョン等込みで表示
> pipdeptree -p flask
Flask==2.1.2
  - click [required: >=8.0, installed: 8.0.4]
    - colorama [required: Any, installed: 0.4.4]
  - itsdangerous [required: >=2.0, installed: 2.1.2]
  - Jinja2 [required: >=3.0, installed: 3.1.2]
    - MarkupSafe [required: >=2.0, installed: 2.1.1]
  - Werkzeug [required: >=2.0, installed: 2.1.2]

参考:https://qiita.com/tmurakami1234/items/b407dc4cc558564882bf

オプション

checkコマンドではGeneral Optionsが使用できます。

オプションを指定する際の記述は以下

pip check [オプション]

download ライブラリをインストールせずダウンロードする

downloadコマンドを使うことでライブラリをダウンロードすることができる。使う場面としてはオフライン環境でライブラリのインストールを行うため、あらかじめダウンロードのみしておく時などがあるらしい。

標準的なダウンロード

以下のコマンドで特にオプション等で指定もしなければ依存関係のパッケージもまとめて最新版がカレントディレクトリにダウンロードされる。
ダウンロードしたファイルを用いてインストールする際はpip installダウンロードしたファイルのパスでインストールできるらしい。
install同様PyPI以外のリポジトリやローカルのファイルからもライブラリのインストールを行える。

pip download ライブラリ名 
pip download -r 要件ファイル 
pip download VCSプロジェクトのURL 
pip download ローカルプロジェクトのパス 
pip download アーカイブのURLかパス 
#試しにnumpyとflaskをダウンロードしてみる。

(piptest) PS C:\WorkSpace\Python\Practice> pip download numpy
Collecting numpy
  Using cached numpy-1.22.3-cp310-cp310-win_amd64.whl (14.7 MB)
Saved c:\workspace\python\practice\numpy-1.22.3-cp310-cp310-win_amd64.whl
Successfully downloaded numpy

(piptest) PS C:\WorkSpace\Python\Practice> pip download flask
Collecting flask
  Using cached Flask-2.1.2-py3-none-any.whl (95 kB)
Collecting Werkzeug>=2.0
  Using cached Werkzeug-2.1.2-py3-none-any.whl (224 kB)
Collecting Jinja2>=3.0
  Using cached Jinja2-3.1.2-py3-none-any.whl (133 kB)
Collecting click>=8.0
  Using cached click-8.1.3-py3-none-any.whl (96 kB)
Collecting itsdangerous>=2.0
  Using cached itsdangerous-2.1.2-py3-none-any.whl (15 kB)
Collecting colorama
  Using cached colorama-0.4.4-py2.py3-none-any.whl (16 kB)
Collecting MarkupSafe>=2.0
  Using cached MarkupSafe-2.1.1-cp310-cp310-win_amd64.whl (17 kB)
Saved c:\workspace\python\practice\flask-2.1.2-py3-none-any.whl
Saved c:\workspace\python\practice\click-8.1.3-py3-none-any.whl
Saved c:\workspace\python\practice\itsdangerous-2.1.2-py3-none-any.whl
Saved c:\workspace\python\practice\jinja2-3.1.2-py3-none-any.whl
Saved c:\workspace\python\practice\werkzeug-2.1.2-py3-none-any.whl
Saved c:\workspace\python\practice\markupsafe-2.1.1-cp310-cp310-win_amd64.whl       
Saved c:\workspace\python\practice\colorama-0.4.4-py2.py3-none-any.whl
Successfully downloaded flask click itsdangerous Jinja2 Werkzeug MarkupSafe colorama

#ダウンロードしたnumpy-1.22.3-cp310-cp310-win_amd64.whlを使ってnumpyをインストールする
#カレントディレクトリにダウンロードしたのでパスはファイル名のみでよい
(piptest) PS C:\WorkSpace\Python\Practice> pip install numpy-1.22.3-cp310-cp310-win_amd64.whl
Processing c:\workspace\python\practice\numpy-1.22.3-cp310-cp310-win_amd64.whl
Installing collected packages: numpy
Successfully installed numpy-1.22.3

オプション、引数

downloadコマンドではGeneral Optionsに加えてDownload Optionsが使用できます。

Download Options
オプション 説明
-c, --constraint Constrain versions using the given constraints file. This option can be used multiple times.
指定された制約ファイルの記述を参照してバージョンを管理する。
-r, --requirement Install from the given requirements file. This option can be used multiple times.
指定された要件ファイルの記述を参照してライブラリをダウンロードする。
--no-deps Don't install package dependencies.
依存関係のライブラリをダウンロードしない。
--global-option Extra global options to be supplied to the setup.py call before the install or bdist_wheel command.
--no-binary Do not use binary packages. Can be supplied multiple times, and each time adds to the existing value. Accepts either ":all:" to disable all binary packages, ":none:" to empty the set (notice the colons), or one or more package names with commas between them (no colons). Note that some packages are tricky to compile and may fail to install when this option is used on them.
--only-binary Do not use source packages. Can be supplied multiple times, and each time adds to the existing value. Accepts either ":all:" to disable all source packages, ":none:" to empty the set, or one or more package names with commas between them. Packages without binary distributions will fail to install when this option is used on them.
--prefer-binary Prefer older binary packages over newer source packages.
--src Directory to check out editable projects into. The default in a virtualenv is "/src". The default for global installs is "/src".
--pre Include pre-release and development versions. By default, pip only finds stable versions.
ダウンロード対象のバージョンにプレリリースバージョンと開発バージョンを含める。デフォルト(--preオプションを使用しなければ)ではインストール対象は安定したバージョンのみとなる。
--require-hashes Require a hash to check each requirement against, for repeatable installs. This option is implied when any package in a requirements file has a --hash option.
--progress-bar Specify type of progress to be displayed [off
--no-build-isolation Disable isolation when building a modern source distribution. Build dependencies specified by PEP 518 must be already installed if this option is used.
--use-pep517 Use PEP 517 for building source distributions (use --no-use-pep517 to force legacy behaviour).
--ignore-requires-python Ignore the Requires-Python information.
-d, --dest Download packages into .
ライブラリを指定のフォルダにダウンロードする。
--platform Only use wheels compatible with . Defaults to the platform of the running system. Use this option multiple times to specify multiple platforms supported by the target interpreter.
--python-version The Python interpreter version to use for wheel and "Requires-Python" compatibility checks. Defaults to a version derived from the running interpreter. The version can be specified using up to three dot-separated integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor version can also be given as a string without dots (e.g. "37" for 3.7.0).
--implementation Only use wheels compatible with Python implementation , e.g. 'pp', 'jy', 'cp', or 'ip'. If not specified, then the current interpreter implementation is used. Use 'py' to force implementation-agnostic wheels.
--abi Only use wheels compatible with Python abi , e.g. 'pypy_41'. If not specified, then the current interpreter abi tag is used. Use this option multiple times to specify multiple abis supported by the target interpreter. Generally you will need to specify --implementation, --platform, and --python-version when using this option.
--no-clean Don't clean up build directories.

オプションを指定する際の記述は以下

pip download [オプション] ライブラリ名 バージョン指定子 [パッケージインデックスオプション] 
pip download [オプション] -r 要件ファイルのパス [パッケージインデックスオプション] 
pip download [オプション] VCSプロジェクトのURL 
pip download [オプション] ローカルプロジェクトのパス 
pip download [オプション] アーカイブのURLかパス 

wheel Wheelアーカイブの構築

wheelコマンドを使うと、wheelというPythonのライブラリの形式であるアーカイブファイル(.whl)を作成できるらしい。作ったライブラリを配布する時とかに使うとのこと。

参考

Wheelファイルの作成

オプションを設定しない場合、以下のコマンドでカレントディレクトリに指定したライブラリと依存関係をまとめたWheelが作成される。

pip wheel ライブラリ名
pip wheel -r 要件ファイルのパス
pip wheel [-e] VCSプロジェクトのURL
pip wheel [-e] ローカルプロジェクトのパス
pip wheel アーカイブのURL、パス
#試しにflaskのwheelファイルを作成してみる

(piptest) PS C:\WorkSpace\Python\Practice> pip wheel flask
Collecting flask
  Using cached Flask-2.1.2-py3-none-any.whl (95 kB)
Collecting itsdangerous>=2.0
  Using cached itsdangerous-2.1.2-py3-none-any.whl (15 kB)
Collecting Werkzeug>=2.0
  Using cached Werkzeug-2.1.2-py3-none-any.whl (224 kB)
Collecting click>=8.0
  Using cached click-8.1.3-py3-none-any.whl (96 kB)
Collecting Jinja2>=3.0
  Using cached Jinja2-3.1.2-py3-none-any.whl (133 kB)
Collecting colorama
  Using cached colorama-0.4.4-py2.py3-none-any.whl (16 kB)
Collecting MarkupSafe>=2.0
  Using cached MarkupSafe-2.1.1-cp310-cp310-win_amd64.whl (17 kB)
Saved c:\workspace\python\practice\flask-2.1.2-py3-none-any.whl
Saved c:\workspace\python\practice\click-8.1.3-py3-none-any.whl
Saved c:\workspace\python\practice\itsdangerous-2.1.2-py3-none-any.whl
Saved c:\workspace\python\practice\jinja2-3.1.2-py3-none-any.whl
Saved c:\workspace\python\practice\werkzeug-2.1.2-py3-none-any.whl
Saved c:\workspace\python\practice\markupsafe-2.1.1-cp310-cp310-win_amd64.whl
Saved c:\workspace\python\practice\colorama-0.4.4-py2.py3-none-any.whl

オプション、引数

wheelコマンドではGeneral Optionsに加えてWheel Optionsが使用できます。

Wheel Options
オプション 説明
-w, --wheel-dir Build wheels into , where the default is the current working directory.
指定したフォルダにwheelファイルを作成する。
--no-binary Do not use binary packages. Can be supplied multiple times, and each time adds to the existing value. Accepts either ":all:" to disable all binary packages, ":none:" to empty the set (notice the colons), or one or more package names with commas between them (no colons). Note that some packages are tricky to compile and may fail to install when this option is used on them.
--only-binary Do not use source packages. Can be supplied multiple times, and each time adds to the existing value. Accepts either ":all:" to disable all source packages, ":none:" to empty the set, or one or more package names with commas between them. Packages without binary distributions will fail to install when this option is used on them.
--prefer-binary Prefer older binary packages over newer source packages.
--no-build-isolation Disable isolation when building a modern source distribution. Build dependencies specified by PEP 518 must be already installed if this option is used.
--use-pep517 Use PEP 517 for building source distributions (use --no-use-pep517 to force legacy behaviour).
-c, --constraint Constrain versions using the given constraints file. This option can be used multiple times.
指定された制約ファイルの記述を参照してバージョンを管理する。
-e, --editable Install a project in editable mode (i.e. setuptools "develop mode") from a local project path or a VCS url.
-r, --requirement Install from the given requirements file. This option can be used multiple times.
指定された要件ファイルの記述を参照してwheelファイルを作成する。
--src Directory to check out editable projects into. The default in a virtualenv is "/src". The default for global installs is "/src".
--ignore-requires-python Ignore the Requires-Python information.
--no-deps Don't install package dependencies.
依存関係のwheelファイルを作成しない。
--progress-bar Specify type of progress to be displayed [off
--no-verify Don't verify if built wheel is valid.
--build-option Extra arguments to be supplied to 'setup.py bdist_wheel'.
--global-option Extra global options to be supplied to the setup.py call before the install or bdist_wheel command.
--pre Include pre-release and development versions. By default, pip only finds stable versions.
Wheelファイルを作成するバージョンにプレリリース版を含める。
--require-hashes Require a hash to check each requirement against, for repeatable installs. This option is implied when any package in a requirements file has a --hash option.
--no-clean Don't clean up build directories.

オプションを指定する際の記述は以下

pip wheel [オプション] ライブラリ名 バージョン指定子 [パッケージインデックスオプション] 
pip wheel [オプション] -r 要件ファイルのパス [パッケージインデックスオプション] 
pip wheel [オプション] VCSプロジェクトのURL 
pip wheel [オプション] ローカルプロジェクトのパス 
pip wheel [オプション] アーカイブのURLかパス 

hash ハッシュ値を計算する

hashコマンドを使うとローカルにあるライブラリのアーカイブファイルのハッシュ値を計算できるらしい。
pipにはハッシュチェックモードというものがありその際に使用するハッシュ値を求めるもとのこと。

ハッシュとは

ハッシュ値とは特定の計算手法で求められる一定の長さの値で、同じ値を再現するのは難しく元データが改変されていないか等を確認するのに使用されたりするとのこと。

ハッシュ値 【hash value】 ダイジェスト値 / digest value / 要約値
ハッシュ値とは、元になるデータから一定の計算手順により求められた固定長の値。その性質から暗号や認証、データ構造などに応用されている。ハッシュ値を求めるための計算手順のことをハッシュ関数、要約関数、メッセージダイジェスト関数などという。
ハッシュ値は元のデータの長さによらず一定の長さとなっており、同じデータからは必ず同じハッシュ値が得られる。実用上は数バイトから数十バイト程度の長さとすることが多い。計算過程で情報の欠損が起きる不可逆な変換が含まれ、ハッシュ値から元のデータを復元することはできない。
ハッシュ値は元のデータの特徴を表す短い符号として利用することができ、データの比較や検索を高速化することができる。例えば、大きな容量のファイルの内容が同一であるかを比較する際に端から順にすべてのデータを照合すれば時間が掛かるが、それぞれハッシュ値を計算しておいて比較すれば一致するかどうかは一瞬で判別することができる。
参考:https://e-words.jp/w/%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4.html

標準のハッシュ値の計算

ハッシュ値の計算は以下のコマンドで実行できる。

pip hash アーカイブデータのパス
#試しにさっきダウンロードしておいたnumpyのwheelファイルのハッシュ値を計算してみる。
#カレントフォルダにダウンロードしたのでファイル名のみで実行
> pip hash numpy-1.22.3-cp310-cp310-win_amd64.whl
numpy-1.22.3-cp310-cp310-win_amd64.whl:
--hash=sha256:08d9b008d0156c70dc392bb3ab3abb6e7a711383c3247b410b39962263576cd4

オプション

hashコマンドではGeneral Optionsに加えてHash Optionsが使用できます。

Hash Options
オプション 説明
-a, --algorithm The hash algorithm to use: one of sha256, sha384, sha512
ハッシュ値を計算するアルゴリズムをsha256sha384sha512の中から選択する。

オプションを指定する際の記述は以下

pip hash [オプション] アーカイブデータのパス

search ライブラリを検索する。

searchコマンドはPyPIのライブラリを検索することができるそうなのですが、実行すると以下のエラー文が表示されました。

> pip search jupyter
ERROR: XMLRPC request failed [code: -32500]
RuntimeError: PyPI's XMLRPC API is currently disabled due to unmanageable load and will be deprecated in the near future. See https://status.python.org/ for more information.

どうやらPyPIのXMLRPC APIが現在無効になっているため検索できないらしいです。
検索してみたときに無効になっていただけなのか、ずっと無効になっているのかは不明ですが、近い将来非推奨になる方法とのことなので違う方法でライブラリを検索してみようと思います。

その他のライブラリ検索方法

  1. webブラウザでPyPIのサイトから検索する
    XMLRPC APIが落ちているのでpipのsearchコマンドで検索できませんでしたが、別にPyPIのサイト自体が落ちているわけではないので、webブラウザでhttps://pypi.org/ にアクセスして検索ボックスで検索すればライブラリは検索できます。

  2. pip-searchを使う
    いちいちブラウザ立ち上げてPyPIで検索するのが面倒な場合、pip-searchというパッケージを利用してライブラリを検索できる。

image.png

(2022.06.07追記)
pip-searchについて記事投稿時は以下のような状況だったが、日を置いて再度インストールした後に使用してみたところ問題なく動いた。

インストールして使ってみたがエラーがでて検索できなかった。
エラーメッセージを読んでみても私の能力では理解も対応もできなかったのであきらめました。

> pip_search hoge
Traceback (most recent call last):
  File "C:\WorkSpace\Python\venv\piptest\Scripts\pip_search-script.py", line 33, in <module>
    sys.exit(load_entry_point('pip-search==0.0.11', 'console_scripts', 'pip_search')())
    snippet.select_one('span[class*="released"]').find("time")[
AttributeError: 'NoneType' object has no attribute 'find'

cache キャッシュを管理する

cacheコマンドでpipのwheelのキャッシュの管理ができるらしい。
(キャッシュを使って何をするとかはわかっていないがそういう機能があるらしい。)
wheelのキャッシュはPyPIにwheelファイルがない場合にpipでライブラリをインストールすると、内部的にwheelファイルを作成しそれを使ってインストールを行っているらしく、その作成されたwheelファイルがキャッシュとして保存されているとのこと。

参考

使い方

cacheコマンドはサブコマンドを組み合わせて使う。

pip cache dir
pip cache info
pip cache list [<pattern>]
pip cache remove <pattern>
pip cache purge

#<pattern>にはパッケージ名かglob式が入る
#[]の項目は省略可

サブコマンド 説明
dir Show the cache directory.
キャッシュの保存されている場所を表示する。
info Show information about the cache.
キャッシュに関する情報を表示する。
list List filenames of packages stored in the cache.
キャッシュに保存されているパッケージのファイル名を一覧表示する。
remove Remove one or more package from the cache.
キャッシュから1つ以上のパッケージを削除する。
purge Remove all items from the cache.
すべてのキャッシュを削除します。
#キャッシュの保存されているディレクトリを表示
> pip cache dir
c:\users\ユーザー名\appdata\local\pip\cache

#キャッシュの情報を表示
> pip cache info
Package index page cache location: c:\users\ユーザー名\appdata\local\pip\cache\http
Package index page cache size: 143.4 MB
Number of HTTP files: 216
Wheels location: c:\users\ユーザー名\appdata\local\pip\cache\wheels
Wheels size: 7.5 kB
Number of wheels: 1

#キャッシュのリストを表示
> pip cache list  
Cache contents:

 - urwid_readline-0.13-py3-none-any.whl (7.5 kB)

#キャッシュの削除(パッケージ名を指定)
> pip cache remove urwid_readline
Files removed: 1

#キャッシュの削除(全キャッシュ削除)
> pip cache purge
Files removed: 217

オプション

cacheコマンドではGeneral Optionsに加えてサブコマンドのlistCache Optionsが使用できます。

Cache Options
オプション 説明
--format Select the output format among: human (default) or abspath
出力形式をhumanabspathかで指定できる。(デフォルトはhuman

オプションを指定する際の記述は以下

pip cache list [<pattern>] [--format=[human, abspath]]
> pip cache list --format=abspath
c:\users\ユーザー名\appdata\local\pip\cache\wheels\58\1d\d8\20c6d76afd5bd205f5f95f19640df9a4e88fc6f1a4c25bb693\urwid_readline-0.13-py3-none-any.whl

config 構成の管理

configコマンドを使うことで構成の管理ができるらしい。
説明を読んでも使いどころ等がさっぱりわからないがこういう機能があるということで整理しておきます。

使い方

cache同様サブコマンドを組み合わせて使用するらしい。

python -m pip config [<file-option>] list
python -m pip config [<file-option>] [--editor <editor-path>] edit
python -m pip config [<file-option>] get command.option
python -m pip config [<file-option>] set command.option value
python -m pip config [<file-option>] unset command.option
python -m pip config [<file-option>] debug
サブコマンド 説明
list List the active configuration (or from the file specified)
アクティブまたは指定したファイルの構成のリストを表示する。
edit Edit the configuration file in an editor
エディターを使用して構成ファイルを編集する。
get Get the value associated with command.option
command.optionに設定された値を取得する。
set Set the command.option=value
command.optionに値を設定する。
unset Unset the value associated with command.optioncommand.optionに設定された値を解除する。
debug List the configuration files and values defined under them
構成ファイルとそれの下に連なる値のリストを表示する。

オプション

configコマンドではGeneral Optionsに加えてConfig Optionsが使用できます。

Config Options
オプション 説明
--editor Editor to use to edit the file. Uses VISUAL or EDITOR environment variables if not provided.
サブコマンドのeditのオプション。editコマンドで使うエディターを指定できる。
--global Use the system-wide configuration file only
システム全体の構成ファイルのみ使用する。
--user Use the user configuration file only
ユーザの構成ファイルのみ使用する
--site Use the current environment configuration file only
現在の仮想環境の構成ファイルのみを使用する

debug デバッグ情報の表示

debgコマンドでデバック情報の表示ができるらしい。
これも説明を読んでも実際何に使うのかがわからないのでそんな機能があるんだな程度に把握しておきます。

使いかた

以下のコマンドでpipを実行する環境のなんやかんやの情報が表示できる。
下の方のCompatible tagsの部分は10個以外は省略されているが、-v--verboseオプションで全部表示できるらしい。

pip debug
> pip debug
WARNING: This command is only meant for debugging. Do not use this with automation for parsing and getting these details, since the output and options of this command may change without notice.
pip version: pip 22.1 from C:\WorkSpace\Python\venv\piptest\lib\site-packages\pip (python 3.10)
sys.version: 3.10.4 (tags/v3.10.4:9d38120, Mar 23 2022, 23:13:41) [MSC v.1929 64 bit (AMD64)]
sys.executable: C:\WorkSpace\Python\venv\piptest\Scripts\python.exe
sys.getdefaultencoding: utf-8
sys.getfilesystemencoding: utf-8
locale.getpreferredencoding: cp932
sys.platform: win32
sys.implementation:
  name: cpython
'cert' config value: Not specified
REQUESTS_CA_BUNDLE: None
CURL_CA_BUNDLE: None
pip._vendor.certifi.where(): C:\WorkSpace\Python\venv\piptest\lib\site-packages\pip\_vendor\certifi\cacert.pem
pip._vendor.DEBUNDLED: False
vendored library versions:
  CacheControl==0.12.11
  colorama==0.4.4
  distlib==0.3.3
  distro==1.7.0
  html5lib==1.1
  msgpack==1.0.3 (Unable to locate actual module version, using vendor.txt specified version)
  packaging==21.3
  pep517==0.12.0
  platformdirs==2.5.2
  pyparsing==3.0.8
  requests==2.27.1
  certifi==2021.10.08
  chardet==4.0.0
  idna==3.3
  urllib3==1.26.9
  rich==12.2.0 (Unable to locate actual module version, using vendor.txt specified version)
  pygments==2.11.2
  typing_extensions==4.2.0 (Unable to locate actual module version, using vendor.txt specified version)
  resolvelib==0.8.1
  setuptools==44.0.0 (Unable to locate actual module version, using vendor.txt specified version)
  six==1.16.0
  tenacity==8.0.1 (Unable to locate actual module version, using vendor.txt specified version)
  tomli==2.0.1
  webencodings==0.5.1 (Unable to locate actual module version, using vendor.txt specified version)
Compatible tags: 36
  cp310-cp310-win_amd64
  cp310-abi3-win_amd64
  cp310-none-win_amd64
  cp39-abi3-win_amd64
  cp38-abi3-win_amd64
  cp37-abi3-win_amd64
  cp36-abi3-win_amd64
  cp35-abi3-win_amd64
  cp34-abi3-win_amd64
  cp33-abi3-win_amd64
  ...
  [First 10 tags shown. Pass --verbose to show all.]

オプション

debugコマンドではGeneral Optionsに加えてDebug Optionsが使用できます。
オプションの説明を読んでも理解が及ばなかったのでhelpで表示される文章をそのまま整理。
(使うときが来たらまた勉強します。)

Debug Options
オプション 説明
--platform Only use wheels compatible with . Defaults to the platform of the running system. Use this option multiple times to specify multiple platforms supported by the target interpreter.
--python-version The Python interpreter version to use for wheel and "Requires-Python" compatibility checks. Defaults to a version derived from the running interpreter. The version can be specified using up to three dot-separated integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor version can also be given as a string without dots (e.g. "37" for 3.7.0).
--implementation Only use wheels compatible with Python implementation , e.g. 'pp', 'jy', 'cp', or 'ip'. If not specified, then the current interpreter implementation is used. Use 'py' to force implementation-agnostic wheels.
--abi Only use wheels compatible with Python abi , e.g. 'pypy_41'. If not specified, then the current interpreter abi tag is used. Use this option multiple times to specify multiple abis supported by the target interpreter. Generally you will need to specify --implementation, --platform, and --python-version when using this option.
7
6
0

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
7
6