目次
文書の過去の版を表示しています。
pip コマンド
pip オプション一覧
コマンド | 説明 |
---|---|
$ python -m pip install --upgrade pip | pip 自体を更新する。 |
$ pip freeze | インストール済みパッケージを一覧表示する。 |
$ pip search Django | パッケージを検索する。 |
$ pip install Django | パッケージをインストールする。 |
$ pip install Django==1.4.2 | パッケージバージョンを指定してインストールする。 |
$ pip install Django -I | インストール済みパッケージを無視して再インストールする。 |
$ pip install Django -U | パッケージをアップグレードする。 |
$ pip uninstall Django | パッケージをアンインストールする。 |
$ pip uninstall Django | パッケージをアンインストールする。 |
$ pip freeze > pkglist.txt $ pip install -r pkglist.txt | venv などの環境を複製する。 |
$ pip freeze > pkglist.txt $ pip uninstall -r pkglist.txt -y $ pip freeze | xargs pip uninstall -y $ pip freeze | grep -v "^-e" | xargs pip uninstall -y | 全パッケージを確認なしでアンインストールする。 |
$ pip -V | バージョンを表示する。 |
pip のヘルプ
$ 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 アップデート警告が出たら
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 を更新する。
$ 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
venv などの環境を複製
pip freeze の出力を保存する。
$ pip freeze > pkglist.txt
pip install の引数に pkglist.txt を指定する。
$ pip install -r pkglist.txt
パッケージのインストールパスを調べる
$ 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 にインストールされている。
pip のダウンロードキャッシュ
キャッシュをクリアしなくても以下の –no-cache-dir オプションでキャッシュを利用しなくなる。
$ pip install django --no-cache-dir
Linux
~/.cache/pip
Mac
~/Library/Caches/pip
Windows
%LocalAppData%\pip\Cache
pip パッケージを使った HTTP URL ダウンローダーの作り方
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