python:pip

文書の過去の版を表示しています。


pip コマンド

読み方的に...😅💦
File:JR Soya-Main-Line Pippu Station-name signboard.jpg - Wikimedia Commons より
読み方的に…😅💦

本家: Python Packaging Authority — PyPA documentation
ソースコード: pypa/pip: The Python package installer
ドキュメント: User Guide - pip documentation v21.1.2

pip オプション一覧

コマンド 説明
$ python -m pip install --upgrade pip
$ python -m pip install -U pip
pip 自体を更新する。
$ pip list
$ pip list -v
$ pip freeze
インストール済みパッケージを一覧表示する。
$ pip search Django
パッケージを検索する。
$ pip install Django
パッケージをインストールする。
$ pip install Django==1.4.2
パッケージバージョンを指定してインストールする。
$ pip install --ignore-installed Django
$ pip install -I Django
インストール済みパッケージを無視して再インストールする。
$ pip install --upgrade Django
$ pip install -U Django
パッケージをアップグレードする。
$ pip uninstall Django
パッケージをアンインストールする。
$ pip freeze > pkglist.txt
$ pip install -r pkglist.txt
venv などの環境を複製する。
$ pip freeze > requirements.txt
$ pip uninstall -r requirements.txt -y
$ pip freeze | xargs pip uninstall -y
$ pip freeze | grep -v "^-e" | xargs pip uninstall -y
全パッケージを確認なしでアンインストールする。
$ pip --version
$ pip -V
バージョンを表示する。

pip の詳細は以下の公式ドキュメントを参照のこと。
Home - pip documentation v21.1.1

$ pip -h
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.
  wheel                       Build wheels from your requirements.
  hash                        Compute hashes of package archives.
  completion                  A helper command used for command completion.
  help                        Show help for commands.

General Options:
  -h, --help                  Show help.
  --isolated                  Run pip in an isolated mode, ignoring environment variables and user
                              configuration.
  -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.
  --proxy <proxy>             Specify a proxy in the form [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 as trusted, even though it does not have valid or any
                              HTTPS.
  --cert <path>               Path to alternate CA bundle.
  --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

pip install <package name> の実行で以下の警告が表示されたら…

WARNING: You are using pip version 19.2.3, however version 20.0.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
警告:pip バージョン 19.2.3 を使用していますが、バージョン 20.0.2 が利用可能です。
'python -m pip install --upgradepip' コマンドを使用してアップグレードすることを検討する必要があります。

pip を更新する。

$ python -m pip install --upgrade pip
Collecting pip
  Downloading https://files.pythonhosted.org/packages/54/0c/d01aa759fdc501a58f431eb594a17495f15b88da142ce14b5845662c13f3/pip-20.0.2-py2.py3-none-any.whl (1.4MB)
     |████████████████████████████████| 1.4MB 731kB/s
Installing collected packages: pip
  Found existing installation: pip 19.2.3
    Uninstalling pip-19.2.3:
      Successfully uninstalled pip-19.2.3
Successfully installed pip-20.0.2

PyPI · The Python Package Index

しばらく使えません😥

$ pip search pandas

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.

Python Infrastructure Status
Python Statusさん (@PythonStatus) / Twitter

pip freeze の出力を保存する。

$ pip freeze > requirements.txt

pip install の引数に requirements.txt を指定する。

$ pip install -r requirements.txt
$ python3 -c "import site; print('\n'.join(site.getsitepackages()))"

Fedora release 33 (Thirty Three)

/usr/local/lib64/python3.9/site-packages
/usr/local/lib/python3.9/site-packages
/usr/lib64/python3.9/site-packages
/usr/lib/python3.9/site-packages

Raspbian GNU/Linux 10 (buster)

/usr/local/lib/python3.7/dist-packages
/usr/lib/python3/dist-packages
/usr/lib/python3.7/dist-packages
$ pip show mercurial
Name: mercurial
Version: 5.6.1
Summary: Fast scalable distributed SCM (revision control, version control) system
Home-page: https://mercurial-scm.org/
Author: Matt Mackall and many others
Author-email: mercurial@mercurial-scm.org
License: GNU GPLv2 or any later version
Location: /usr/local/lib/python3.7/dist-packages
Requires:
Required-by:

パッケージは Location: /usr/local/lib/python3.7/dist-packages にインストールされている。

キャッシュをクリアしなくても以下の --no-cache-dir オプションでキャッシュを利用しなくなる。

$ pip install django --no-cache-dir
~/.cache/pip
~/Library/Caches/pip
%LocalAppData%\pip\Cache

pip 19.2.2 で動作を確認した。
以下は pip パッケージを利用した HTTP URL のダウンローダーのコードである。
この download_http_url() 関数を利用すれば、パッケージではない様々なファイルを pip と同様に進行状況を表示しながらダウンロードする事ができる。

pip_downloader.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cgi
import mimetypes
import os
 
from pip._internal.download import PipSession
from pip._internal.models.link import Link
from pip._vendor.requests.models import CONTENT_CHUNK_SIZE
from pip._internal.utils.misc import splitext, consume, format_size
from pip._internal.utils.ui import DownloadProgressProvider
from pip._vendor import requests
 
import logging
 
logger = logging.getLogger(__name__)
 
def download_http_url(
    url,  # type: str
    download_dir,  # type: str
    hashes=None,   # type: Optional[Hashes]
    progress_bar='on'   # type: str
):
    logger.debug('download_http_url("%s", "%s")', url, download_dir)
    link = Link(url)
    session = PipSession()
 
    def _download_url(
        resp,  # type: Response
        link,  # type: Link
        content_file,  # type: IO
        hashes,  # type: Optional[Hashes]
        progress_bar  # type: str
    ):
        # type: (...) -> None
        try:
            total_length = int(resp.headers['content-length'])
        except (ValueError, KeyError, TypeError):
            total_length = 0
 
        cached_resp = getattr(resp, 'from_cache', False)
        if cached_resp:
            show_progress = False
        elif total_length > (40 * 1000):
            show_progress = True
        elif not total_length:
            show_progress = True
        else:
            show_progress = False
 
        def resp_read(chunk_size):
            try:
                # Special case for urllib3.
                for chunk in resp.raw.stream(
                        chunk_size,
                        decode_content=False):
                    yield chunk
            except AttributeError:
                # Standard file-like object.
                while True:
                    chunk = resp.raw.read(chunk_size)
                    if not chunk:
                        break
                    yield chunk
 
        def written_chunks(chunks):
            for chunk in chunks:
                content_file.write(chunk)
                yield chunk
 
        def _progress_indicator(iterable, *args, **kwargs):
            return iterable
 
        progress_indicator = _progress_indicator
 
        if show_progress:  # We don't show progress on cached responses
            progress_indicator = DownloadProgressProvider(progress_bar,
                                                            max=total_length)
            if total_length:
                print('Downloading {} ({})'.format(url, format_size(total_length)))
            else:
                print(f'Downloading {link.url}')
        elif cached_resp:
            print(f'Using cached {link.url}')
        else:
            print(f'Downloading {link.url}')
 
        print(f'Downloading from URL {link}')
 
        downloaded_chunks = written_chunks(
            progress_indicator(
                resp_read(CONTENT_CHUNK_SIZE),
                CONTENT_CHUNK_SIZE
            )
        )
        if hashes:
            hashes.check_against_chunks(downloaded_chunks)
        else:
            consume(downloaded_chunks)
 
    # type: (...) -> Tuple[str, str]
    """Download link url into temp_dir using provided session"""
    target_url = link.url.split('#', 1)[0]
    try:
        resp = session.get(
            target_url,
            headers={"Accept-Encoding": "identity"},
            stream=True,
        )
        resp.raise_for_status()
    except requests.HTTPError as exc:
        print('HTTP error {} while getting {}'.format(exc.response.status_code, link))
        raise
 
    content_type = resp.headers.get('content-type', '')
    filename = link.filename  # fallback
    # Have a look at the Content-Disposition header for a better guess
    content_disposition = resp.headers.get('content-disposition')
    if content_disposition:
        # type: (str, str) -> str
        def sanitize_content_filename(filename):
            # type: (str) -> str
            """
            Sanitize the "filename" value from a Content-Disposition header.
            """
            return os.path.basename(filename)
 
        """
        Parse the "filename" value from a Content-Disposition header, and
        return the default filename if the result is empty.
        """
        _type, params = cgi.parse_header(content_disposition)
        filename = params.get('filename')
        if filename:
            # We need to sanitize the filename to prevent directory traversal
            # in case the filename contains ".." path parts.
            filename = sanitize_content_filename(filename)
 
    ext = splitext(filename)[1]  # type: Optional[str]
    if not ext:
        ext = mimetypes.guess_extension(content_type)
        if ext:
            filename += ext
    if not ext and link.url != resp.url:
        ext = os.path.splitext(resp.url)[1]
        if ext:
            filename += ext
    file_path = os.path.join(download_dir, filename)
    with open(file_path, 'wb') as content_file:
        _download_url(resp, link, content_file, hashes, progress_bar)
    return file_path, content_type

pip_downloader.py の使い方。

main.py
#!/usr/bin/env python3
## -*- coding: utf-8 -*-
import os
# pip_downloader.py をインポートする
import pip_downloader
 
# メイン処理
def main():
    pip_downloader.download_http_url(
        'https://download.visualstudio.microsoft.com/download/pr/7b196ac4-65a9-4fde-b720-09b5339dbaba/78df39539625fa4e6c781c6a2aca7b4f/vs_community.exe',
        os.environ['USERPROFILE']
    )
 
# スクリプト起動時に main() を実行
if __name__ == "__main__":
    main()

main.py 実行する。

> python main.py
Downloading https://download.visualstudio.microsoft.com/download/pr/7b196ac4-65a9-4fde-b720-09b5339dbaba/78df39539625fa4e6c781c6a2aca7b4f/vs_community.exe (1.3MB)
Downloading from URL https://download.visualstudio.microsoft.com/download/pr/7b196ac4-65a9-4fde-b720-09b5339dbaba/78df39539625fa4e6c781c6a2aca7b4f/vs_community.exe
   |████████████████████████████████| 1.4MB 3.3MB/s

古いパッケージの一覧表示が失敗する。

$ python3 -m pip list -o

Exception:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/base_command.py", line 143, in main
    status = self.run(options, args)
  File "/usr/lib/python3/dist-packages/pip/_internal/commands/list.py", line 138, in run
    packages = self.get_outdated(packages, options)
  File "/usr/lib/python3/dist-packages/pip/_internal/commands/list.py", line 149, in get_outdated
    dist for dist in self.iter_packages_latest_infos(packages, options)
  File "/usr/lib/python3/dist-packages/pip/_internal/commands/list.py", line 150, in <listcomp>
    if dist.latest_version > dist.parsed_version
TypeError: '>' not supported between instances of 'Version' and 'Version'

ディストリビューションの pip を最新版に更新する場合

$ python3 -m pip -V
pip 18.1 from /usr/lib/python3/dist-packages/pip (python 3.7)

ディストリビューションの古い python3-pip パッケージだと不具合がある。

$ python3 -m pip list -v
Package    Version Location                       Installer
---------- ------- ------------------------------ ---------
pip        18.1    /usr/lib/python3/dist-packages
setuptools 40.8.0  /usr/lib/python3/dist-packages

pip を最新版に更新する。

$ python3 -m pip install -U pip
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting pip
  Downloading https://files.pythonhosted.org/packages/cd/6f/43037c7bcc8bd8ba7c9074256b1a11596daa15555808ec748048c1507f08/pip-21.1.1-py3-none-any.whl (1.5MB)
    100% |████████████████████████████████| 1.6MB 34kB/s
Installing collected packages: pip
Successfully installed pip-21.1.1

pip list -o が正常に利用できることを確認する。

$ python3 -m pip list -o
Package    Version Latest Type
---------- ------- ------ -----
setuptools 40.8.0  56.2.0 wheel
$ python3 -m pip list -v
Package    Version Location                                         Installer
---------- ------- ------------------------------------------------ ---------
pip        21.1.1  /home/tomoyan/.local/lib/python3.7/site-packages pip
setuptools 40.8.0  /usr/lib/python3/dist-packages

仮想環境の pip を最新版に更新する場合

(py3_venv) $ pip -V
pip 18.1 from /home/tomoyan/py3_venv/lib/python3.7/site-packages/pip (python 3.7)

pip を最新版に更新する。

(py3_venv) $ python -m pip install -U pip
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting pip
  Downloading https://files.pythonhosted.org/packages/cd/6f/43037c7bcc8bd8ba7c9074256b1a11596daa15555808ec748048c1507f08/pip-21.1.1-py3-none-any.whl (1.5MB)
    100% |████████████████████████████████| 1.6MB 40kB/s
Installing collected packages: pip
  Found existing installation: pip 18.1
    Uninstalling pip-18.1:
      Successfully uninstalled pip-18.1
Successfully installed pip-21.1.1

更新後のバージョン確認。

(py3_venv) $ pip -V
pip 21.1.1 from /home/tomoyan/py3_venv/lib/python3.7/site-packages/pip (python 3.7)

pip list -o が正常に利用できることを確認する。

(py3_venv) $ pip list -o
Package    Version  Latest    Type
---------- -------- --------- -----
Django     3.2.1    3.2.3     wheel
pytz       2020.4   2021.1    wheel
setuptools 40.8.0   56.2.0    wheel
supervisor 4.2.1    4.2.2     wheel
youtube-dl 2021.1.8 2021.4.26 wheel

システムの古い pip ラッパー📯が新しい pip モジュールを実行してしまう場合

$ pip3 -V
WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.
Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.
To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.
pip 21.1.1 from /home/pi/.local/lib/python3.7/site-packages/pip (python 3.7)
警告: pip は古いスクリプトラッパーによって呼び出されています。これは、pip の将来のバージョンでは失敗します。
根本的な問題を修正するためのアドバイスについては、https://github.com/pypa/pip/issues/5599 を参照してください。
この問題を回避するには、pipを直接実行する代わりに、「-m pip」を使用して Python を呼び出すことができます。
/home/pi/.local/lib/python3.7/site-packages/pip からの pip21.1.1 (python 3.7)

ImportError in system pip wrappers after an upgrade · Issue #5599 · pypa/pip · GitHub

回避方法は pip のモジュールを直接実行する。

$ python3 -m pip -V
  • python/pip.1623125587.txt.gz
  • 最終更新: 2021/06/08 13:13
  • by ともやん