python:pip

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

コマンド 説明

$ 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 freeze --local | grep -v '^\-e' | cut -d = -f 1 | xargs pip install -U pip

全パッケージをアップグレードする。

$ pip list --outdated | sed 1,2d | cut -f 1 -d ' ' | xargs --no-run-if-empty pip install --upgrade

$ pip list -o | sed 1,2d | cut -f 1 -d ' ' | xargs -r pip install -U

更新可能がパッケージをすべてアップグレードする。

$ pip uninstall Django

パッケージをアンインストールする。

$ pip freeze > requirements.txt
$ python -m pip install -U pip
$ pip install -r requirements.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 freeze --user | grep -v "^-e" | cut -f 1 -d '=' | 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.
  inspect                     Inspect the python environment.
  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.
  --python <python>           Run pip with the specified Python interpreter.
  -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.

参考: User Guide#Command Completion - pip documentation v23.0.1
pip のコマンド補完が効いていない状態🤔

$ pip -> Tab キーを押す

pip             pip-3.11        pip3.11         pipewire        pipewire-avb    
pip-3           pip3            pipetty         pipewire-aes67  pipewire-pulse

pip のコマンド補完を zsh に設定する🤔

$ python -m pip completion --zsh

# pip zsh completion start
function _pip_completion {
  local words cword
  read -Ac words
  read -cn cword
  reply=( $( COMP_WORDS="$words[*]" \
             COMP_CWORD=$(( cword-1 )) \
             PIP_AUTO_COMPLETE=1 $words[1] 2>/dev/null ))
}
compctl -K _pip_completion /usr/bin/python -m pip
# pip zsh completion end

$ python -m pip completion --zsh >> ~/.zprofile
$ . ~/.zprofile 

pip のコマンド補完を bash に設定する🤔

$ python -m pip completion --bash

# pip bash completion start
_pip_completion()
{
    COMPREPLY=( $( COMP_WORDS="${COMP_WORDS[*]}" \
                   COMP_CWORD=$COMP_CWORD \
                   PIP_AUTO_COMPLETE=1 $1 2>/dev/null ) )
}
complete -o default -F _pip_completion /usr/bin/python -m pip
# pip bash completion end

$ python -m pip completion --bash >> ~/.profile
$ . ~/.profile 

"pip "(pip のあとにスペースを1つ TAB キーを入力) pip のコマンド補完が効くようになる😍
zsh の場合

┌──(tomoyan  WICKED-BEAT)-[~] └─$ pip -> Tab キーを押す
check -- verify installed packages have compatible dependencies download -- download packages freeze -- output installed packages in requirements format hash -- compute hashes of package archives help -- show available commands install -- install packages list -- list installed packages search -- search PyPI for packages show -- show information about installed packages uninstall -- uninstall packages wheel -- build wheels from your requirements

bash の場合

$ pip -> Tab キーを押す
cache       completion  debug       freeze      help        inspect     list        show        wheel
check       config      download    hash        index       install     search      uninstall   

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

[notice] A new release of pip available: 22.2.2 -> 23.0.1
[notice] To update, run: pip install --upgrade pip

[お知らせ] pip の新しいリリース: 22.2.2 -> 23.0.1
[お知らせ] 更新するには、次を実行します: pip install --upgrade pip

pip を更新する。

(pyMusicEnv) $ python -m pip install -U pip

Requirement already satisfied: pip in ./pyMusicEnv/lib64/python3.11/site-packages (22.2.2)
Collecting pip
  Using cached pip-23.0.1-py3-none-any.whl (2.1 MB)
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 22.2.2
    Uninstalling pip-22.2.2:
      Successfully uninstalled pip-22.2.2
Successfully installed pip-23.0.1

PyPI · The Python Package Index

しばらく使えません…😥

$ pip search pandas

ERROR: XMLRPC request failed [code: -32500]
RuntimeError: PyPI no longer supports 'pip search' (or XML-RPC search). Please use https://pypi.org/search (via a browser) instead. See https://warehouse.pypa.io/api-reference/xml-rpc.html#deprecated-methods 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

公式: site — Site-specific configuration hook (翻訳)

$ python -m site

sys.path = [
    '/home/tomoyan',
    '/usr/lib64/python311.zip',
    '/usr/lib64/python3.11',
    '/usr/lib64/python3.11/lib-dynload',
    '/home/tomoyan/.local/lib/python3.11/site-packages',
    '/usr/lib64/python3.11/site-packages',
    '/usr/lib/python3.11/site-packages',
]
USER_BASE: '/home/tomoyan/.local' (exists)
USER_SITE: '/home/tomoyan/.local/lib/python3.11/site-packages' (exists)
ENABLE_USER_SITE: True

グローバル (Global) インストールの場合🤔

$ python -c "import site; print('\n'.join(site.getsitepackages()))"

Python 2 系が共存しているシステムは無いと思うけど Python 3 を明示して実行する場合は python3 を実行する🤔

$ python3 -c "import site; print('\n'.join(site.getsitepackages()))"

Fedora release 37 (Thirty Seven)

/usr/local/lib64/python3.11/site-packages
/usr/local/lib/python3.11/site-packages
/usr/lib64/python3.11/site-packages
/usr/lib/python3.11/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

$ pip3 cache info

Package index page cache location: /home/tomoyan/.cache/pip/http
Package index page cache size: 905.6 MB
Number of HTTP files: 976
Locally built wheels location: /home/tomoyan/.cache/pip/wheels
Locally built wheels size: 482 kB
Number of locally built wheels: 4

~/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

システムの Python バージョンがマイナーアップデートした事による影響も考えられるので、以下の文献も参照のこと🤔
仮想環境で ModuleNotFoundError: No module named 'pip' が発生する😇

$ . 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

または、ensurepip を実行する。
公式: コマンドラインから pip を実行できることを確実にする - パッケージをインストールする — Python Packaging User Guide

(pyJupyterLab) $ python3 -m ensurepip --default-pip


(pyJupyterLab) $ pip


Usage:   
  pip <command> [options]

Commands:
  install                     Install packages.
  download                    Download packages.
  uninstall                   Uninstall packages.
  freeze                      Output installed packages in requirements format.
  inspect                     Inspect the python environment.
  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.
  --python <python>           Run pip with the specified Python interpreter.
  -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 install -U pip

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 が正常に利用できることを確認する。

$ 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 -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 24.0 from /home/tomoyan/.local/lib/python3.12/site-packages/pip (python 3.12)

警告: pip は古いスクリプト ラッパーによって呼び出されています。これは、pip の将来のバージョンでは失敗します。
根本的な問題を修正するためのアドバイスについては、https://github.com/pypa/pip/issues/5599 を参照してください。
この問題を回避するには、pip を直接実行する代わりに、「-m pip」を使用して Python を呼び出すことができます。
/home/tomoyan/.local/lib/python3.12/site-packages/pip からの pip 24.0 (Python 3.12)

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

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

$ python -m pip -V

pip 24.0 from /home/tomoyan/.local/lib/python3.12/site-packages/pip (python 3.12)

解決の糸口😅

$ which pip && python -s -m pip -V && python -m pip -V && echo '---- ✂  ----' && echo $PATH | grep :

/usr/local/bin/pip
pip 23.2.1 from /usr/lib/python3.12/site-packages/pip (python 3.12)
pip 24.0 from /home/tomoyan/.local/lib/python3.12/site-packages/pip (python 3.12)
---- ✂  ----
/home/tomoyan/miniforge3/condabin:/home/tomoyan/micromamba/bin:/home/tomoyan/.cargo/bin:/home/tomoyan/.anyenv/envs/nodenv/shims:/home/tomoyan/.anyenv/envs/nodenv/bin:/home/tomoyan/.anyenv/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/tomoyan/.local/bin:/home/tomoyan/.local/bin

  • python/pip.txt
  • 最終更新: 2024/03/28 01:58
  • by ともやん