python:pip

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


pip - Python パッケージ管理システム

読み方的に...😅💦
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 list --verbose
$ pip freeze
インストール済みパッケージを一覧表示する。
$ pip list -o
$ pip list --outdated
インストール済みのうち古くなっているパッケージを一覧表示する。
$ pip search Django
パッケージを検索する。
$ pip install Django
パッケージをインストールする。
$ pip install Django==1.4.2
パッケージバージョンを指定してインストールする。
$ pip install --ignore-installed Django
$ pip install -I Django
インストール済みパッケージを無視して再インストールする。
$ pip install wxpython -I --no-cache-dir
インストール済みとキャッシュ有無を無視してインストールする。
$ 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
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.
  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.
  --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.
  --no-input                  Disable prompting for input.
  --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 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 install <package name> の実行で以下の警告が表示されたら…

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

pip を更新する。

$ python -m pip install --upgrade pip
Collecting pip
  Using cached pip-21.3-py3-none-any.whl (1.7 MB)
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 21.1.1
    Uninstalling pip-21.1.1:
      Successfully uninstalled pip-21.1.1
Successfully installed pip-21.3

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
$ pip list -o
Package           Version   Latest    Type
----------------- --------- --------- -----
anyio             3.2.1     3.3.4     wheel
argon2-cffi       20.1.0    21.1.0    wheel
bleach            3.3.0     4.1.0     wheel
certifi           2021.5.30 2021.10.8 wheel
cffi              1.14.5    1.15.0    wheel
debugpy           1.3.0     1.5.0     wheel
decorator         5.0.9     5.1.0     wheel
GitPython         3.1.18    3.1.24    wheel
idna              2.10      3.3       wheel
ipykernel         6.0.1     6.4.1     wheel
ipython           7.25.0    7.28.0    wheel
Jinja2            3.0.1     3.0.2     wheel
jsonschema        3.2.0     4.1.0     wheel
jupyter-client    6.1.12    7.0.6     wheel
jupyter-core      4.7.1     4.8.1     wheel
jupyter-server    1.9.0     1.11.1    wheel
jupyterlab        3.0.16    3.2.0     wheel
jupyterlab-git    0.30.1    0.33.0    wheel
jupyterlab-server 2.6.0     2.8.2     wheel
kiwisolver        1.3.1     1.3.2     wheel
matplotlib        3.4.2     3.4.3     wheel
matplotlib-inline 0.1.2     0.1.3     wheel
nbclassic         0.3.1     0.3.2     wheel
nbclient          0.5.3     0.5.4     wheel
nbconvert         6.1.0     6.2.0     wheel
notebook          6.4.0     6.4.4     wheel
numpy             1.21.0    1.21.2    wheel
pandas            1.3.0     1.3.3     wheel
pandocfilters     1.4.3     1.5.0     wheel
Pillow            8.3.0     8.4.0     wheel
prompt-toolkit    3.0.19    3.0.20    wheel
Pygments          2.9.0     2.10.0    wheel
pyopencl          2021.2.6  2021.2.8  wheel
python-dateutil   2.8.1     2.8.2     wheel
pytools           2021.2.7  2021.2.8  sdist
pytz              2021.1    2021.3    wheel
pyzmq             22.1.0    22.3.0    wheel
requests          2.25.1    2.26.0    wheel
Send2Trash        1.7.1     1.8.0     wheel
setuptools        53.0.0    58.2.0    wheel
smmap             4.0.0     5.0.0     wheel
terminado         0.10.1    0.12.1    wheel
traitlets         5.0.5     5.1.0     wheel
urllib3           1.26.6    1.26.7    wheel
voila             0.2.10    0.2.16    wheel
websocket-client  1.1.0     1.2.1     wheel
$ 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
$ . pyJupyterLab/bin/activate
(pyJupyterLab) $ pip install -U jupyterlab
Traceback (most recent call last):
  File "/home/tomoyan/pyJupyterLab/bin/pip", line 5, in <module>
    from pip._internal.cli.main import main
ModuleNotFoundError: No module named 'pip'

https://bootstrap.pypa.io/get-pip.py で再インストールして治す🤤

(pyJupyterLab) $ curl -sS https://bootstrap.pypa.io/get-pip.py | python

Collecting pip
  Downloading pip-22.1-py3-none-any.whl (2.1 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.1/2.1 MB 3.1 MB/s eta 0:00:00
Collecting setuptools
  Downloading setuptools-62.3.2-py3-none-any.whl (1.2 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.2/1.2 MB 11.4 MB/s eta 0:00:00
Collecting wheel
  Downloading wheel-0.37.1-py2.py3-none-any.whl (35 kB)
Installing collected packages: wheel, setuptools, pip
Successfully installed pip-22.1 setuptools-62.3.2 wheel-0.37.1

(pyJupyterLab) $ pip
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.

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

$ 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.1653102430.txt.gz
  • 最終更新: 2022/05/21 12:07
  • by ともやん