pip install#
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.
Overview#
pip install has several stages:
Identify the base requirements. The user supplied arguments are processed here.
Resolve dependencies. What will be installed is determined here.
Build wheels. All the dependencies that can be are built into wheels.
Install the packages (and uninstall anything being upgraded/replaced).
Note that pip install prefers to leave the installed version as-is unless —upgrade is specified.
Argument Handling#
When looking at the items to be installed, pip checks what type of item each is, in the following order:
Project or archive URL.
Local directory (which must contain a setup.py , or pip will report an error).
Local file (a sdist or wheel format archive, following the naming conventions for those formats).
A requirement, as specified in PEP 440.
Each item identified is added to the set of requirements to be satisfied by the install.
Working Out the Name and Version#
For each candidate item, pip needs to know the project name and version. For wheels (identified by the .whl file extension) this can be obtained from the filename, as per the Wheel spec. For local directories, or explicitly specified sdist files, the setup.py egg_info command is used to determine the project metadata. For sdists located via an index, the filename is parsed for the name and project version (this is in theory slightly less reliable than using the egg_info command, but avoids downloading and processing unnecessary numbers of files).
Any URL may use the #egg=name syntax (see VCS Support ) to explicitly state the project name.
Satisfying Requirements#
Once pip has the set of requirements to satisfy, it chooses which version of each requirement to install using the simple rule that the latest version that satisfies the given constraints will be installed (but see here for an exception regarding pre-release versions). Where more than one source of the chosen version is available, it is assumed that any source is acceptable (as otherwise the versions would differ).
Obtaining information about what was installed#
The install command has a —report option that will generate a JSON report of what pip has installed. In combination with the —dry-run and —ignore-installed it can be used to resolve a set of requirements without actually installing them.
The report can be written to a file, or to standard output (using —report — in combination with —quiet ).
The format of the JSON report is described in Installation Report .
Installation Order#
This section is only about installation order of runtime dependencies, and does not apply to build dependencies (those are specified using PEP 518).
As of v6.1.0, pip installs dependencies before their dependents, i.e. in “topological order.” This is the only commitment pip currently makes related to order. While it may be coincidentally true that pip will install things in the order of the install arguments or in the order of the items in a requirements file, this is not a promise.
In the event of a dependency cycle (aka “circular dependency”), the current implementation (which might possibly change later) has it such that the first encountered member of the cycle is installed last.
For instance, if quux depends on foo which depends on bar which depends on baz, which depends on foo:
Prior to v6.1.0, pip made no commitments about install order.
The decision to install topologically is based on the principle that installations should proceed in a way that leaves the environment usable at each step. This has two main practical benefits:
Concurrent use of the environment during the install is more likely to work.
A failed install is less likely to leave a broken environment. Although pip would like to support failure rollbacks eventually, in the mean time, this is an improvement.
Although the new install order is not intended to replace (and does not replace) the use of setup_requires to declare build dependencies, it may help certain projects install from sdist (that might previously fail) that fit the following profile:
They have build dependencies that are also declared as install dependencies using install_requires .
python setup.py egg_info works without their build dependencies being installed.
For whatever reason, they don’t or won’t declare their build dependencies using setup_requires .
Requirements File Format
This section has been moved to Requirements File Format .
This section has been moved to Requirement Specifiers .
Pre-release Versions#
Starting with v1.4, pip will only install stable versions as specified by pre-releases by default. If a version cannot be parsed as a compliant PEP 440 version then it is assumed to be a pre-release.
If a Requirement specifier includes a pre-release or development version (e.g. >=0.0.dev0 ) then pip will allow pre-release and development versions for that requirement. This does not include the != flag.
The pip install command also supports a —pre flag that enables installation of pre-releases and development releases.
This is now covered in VCS Support .
Finding Packages#
pip searches for packages on PyPI using the HTTP simple interface, which is documented here and there.
pip offers a number of package index options for modifying how packages are found.
pip looks for packages in a number of places: on PyPI (if not disabled via —no-index ), in the local filesystem, and in any additional repositories specified via —find-links or —index-url . There is no ordering in the locations that are searched. Rather they are all checked, and the “best” match for the requirements (in terms of version number — see PEP 440 for details) is selected.
SSL Certificate Verification
This is now covered in HTTPS Certificates .
This is now covered in Caching .
This is now covered in Caching .
Hash checking mode
This is now covered in Secure installs .
Local Project Installs
Build System Interface
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.
Don’t install package dependencies.
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.
Don’t actually install anything, just print what would be. Can be used in combination with —ignore-installed to ‘resolve’ the requirements.
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.
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.
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).
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.
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.
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.)
Install everything relative to this alternate root directory.
Installation prefix where lib, bin and other top-level folders are placed
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”.
Upgrade all specified packages to the newest available version. The handling of dependencies depends on the upgrade-strategy used.
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).
Reinstall all packages even if they are already up-to-date.
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 the Requires-Python information.
Disable isolation when building a modern source distribution. Build dependencies specified by PEP 518 must be already installed if this option is used.
Use PEP 517 for building source distributions (use —no-use-pep517 to force legacy behaviour).
Check the build dependencies when PEP517 is used.
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.
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.
Extra global options to be supplied to the setup.py call before the install or bdist_wheel command.
Compile Python source files to bytecode
Do not compile Python source files to bytecode
Do not warn when installing scripts outside PATH
Do not warn about broken dependencies
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.
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 older binary packages over newer source packages.
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.
Specify whether the progress bar should be used [on, off] (default: on)
Action if pip is run as a root user. By default, a warning message is shown.
Generate a JSON file describing what pip did to install the provided requirements. Can be used in combination with —dry-run and —ignore-installed to ‘resolve’ the requirements. When — is used as file name it writes to stdout. When writing to stdout, please combine with the —quiet option to avoid mixing pip logging output with JSON output.
Don’t clean up build directories.
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 URLs of package indexes to use in addition to —index-url. Should follow the same rules as —index-url.
Ignore package index (only looking at —find-links URLs instead).
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.
Examples#
Install SomePackage and its dependencies from PyPI using Requirement Specifiers
Менеджер пакетов PIP. Гайд по использованию
P IP — это менеджер пакетов. Он позволяет устанавливать и управлять пакетами на Python.
Представьте себе ситуацию: вы собираете проект и подключаете множество сторонних библиотек для реализации своей задачи. Если это делать вручную, процесс выглядит примерно так:
- вы заходите на сайт, выбираете нужную версию пакета;
- скачиваете ее, разархивируете, перекидываете в папку проекта;
- подключаете, прописываете пути, тестируете.
Вполне вероятно, что эта версия библиотеки вообще не подходит, и весь процесс повторяется заново. А если таких библиотек 10? Устанавливать их вручную?
Менеджер пакетов PIP — решает данную проблему. Весь процесс установки пакета сводится к выполнению консольной команды pip install package-name . Несложно представить, сколько времени это экономит.
Если вы работали с другими языками программирования, концепция pip может показаться вам знакомой. Pip похож на npm (в Javascript), composer (в PHP) или gem (в Ruby).
Pip является стандартным менеджером пакетов в Python
Pip или pip3?
В зависимости от того, какая версия Python установлена в системе, может потребоваться использовать pip3 вместо pip.
Если вы не знаете какая версия Python установлена на вашей системе, выполните следующие команды:
- python —version — для Python 2.x
- python3 —version — для Python 3.x
- python3.8 —version — для Python 3.8.x
Советуем использовать версию Python 3.6 и выше
Если команда "python" не найдена, установите Python по инструкции из предыдущей статьи.
Далее нужно убедиться, что сам PIP установлен и работает корректно. Узнать это поможет команда:
Команда отобразит в консоли версию pip, путь до pip и версию python, для которой в дальнейшем будут устанавливаться пакеты:
pip 19.2.3 from /usr/local/lib/python3.8/site-packages/pip (python 3.8)
☝️ Важный момент : в зависимости от того, какую версию Python вы будете использовать, команда может выглядеть как pip , pip3 или pip3.8
Альтернативный вариант вызова pip:
python3.7 -m pip install package-name
Флаг -m сообщает Python-у запустить pip как исполняемый модуль.
Если pip не установлен
Pip поставляется вместе с Python, и доступен после его установки. Если по какой-то причине pip не установлен на вашей системе, установить его будет не сложно.
Windows
- Скачайте файл get-pip.py и сохраните у себя на компьютере.
- Откройте командную строку и перейдите в папку, в которой сохранен get-pip.py .
- В командной строке выполните команду: python get-pip.py или python3 get-pip.py .
- PIP установлен !
Linux (Ubuntu и Debian)
Прежде, чем перейти к непосредственному описанию, хотим отметить, что все команды, описанные ниже, используются от имени root пользователя. Если же вы являетесь обычным пользователем на компьютере, то потребуется использовать команду sudo , чтобы получить привилегии root.
Для Питона 2-й версии, выполните команду:
apt-get install python-pip
Для Питона 3-ей версии:
apt-get install python3-pip
MacOS
- скачайте файл get-pip.py командой curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py ;
- запустите скачанный файл командой: python get-pip.py или python3 get-pip.py .
Должна появиться запись Successfully Installed. Процесс закончен, можно приступать к работе с PIP на MacOS!
Как обновить PIP
Иногда, при установке очередного пакета, можно видеть сообщение о том, что доступна новая версия pip.
WARNING: You are using pip version 19.2.3, however version 19.3.1 is available.
А в следующей за ней строке
You should consider upgrading via the 'python -m pip install —upgrade pip' command.
указана команда для обновления pip:
python -m pip install —upgrade pip
Команды PIP
Синтаксис pip выглядит следующим образом: pip + команда + доп. опции
pip <command> [options]
Со всеми командами pip можно ознакомиться, выполнив pip help . Информацию по конкретной команде выведет pip help <command> .
Рассмотрим команды pip:
- pip install package-name — устанавливает последнюю версию пакета;
- pip install package-name==4.8.2 — устанавливает пакет версии 4.8.2;
- pip install package-name —upgrade — обновляет версию пакета;
- pip download — скачивает пакеты;
- pip uninstall — удаляет пакеты;
- pip freeze — выводит список установленных пакетов в необходимом формате ( обычно используется для записи в requirements.txt );
- pip list — выводит список установленных пакетов;
- pip list —outdated — выводит список устаревших пакетов;
- pip show — показывает информацию об установленном пакете;
- pip check — проверяет установленные пакеты на совместимость зависимостей;
- pip search — по введенному названию, ищет пакеты, опубликованные в PyPI;
- pip wheel — собирает wheel-архив по вашим требованиям и зависимостям;
- pip hash — вычисляет хеши архивов пакетов;
- pip completion — вспомогательная команда используется для завершения основной команды;
- pip help — помощь по командам.
Пример работы с пакетами
PIP позволяет устанавливать, обновлять и удалять пакеты на компьютере. Ниже попробуем разобраться с работой менеджера pip на примере парсинга названий свежих статей на сайте habr.com.
- установим нужные пакеты;
- импортируем пакет в свой скрипт;
- разберемся, что такое requirements.txt ;
- обновим/удалим установленные пакеты.
Шаг #1 Установка.
Для начала, нам необходимо установить beautifulsoup4 — библиотеку для парсинга информации с веб-сайтов.
pip3 install beautifulsoup4
pip найдет последнюю версию пакета в официальном репозитории pypi.org . После скачает его со всеми необходимыми зависимостями и установит в вашу систему. Если вам нужно установить определенную версию пакета, укажите её вручную:
pip3 install beautifulsoup4==4.8.2
Данная команда способна даже перезаписать текущую версию на ту, что вы укажите.
Также для работы beautifulsoup нам понадобится пакет lxml :
pip install lxml
☝️ Важный момент : по умолчанию pip устанавливает пакеты глобально. Это может привести к конфликтам между версиями пакетов. На практике, чтобы изолировать пакеты текущего проекта, создают виртуальное окружение (virtualenv).
Шаг #2 Импортирование в скрипте.
Для того чтобы воспользоваться функционалом установленного пакета, подключим его в наш скрипт, и напишем простой парсер:
from urllib.request import urlopen from bs4 import BeautifulSoup # скачиваем html page = urlopen("https://habr.com/ru/top/") content = page.read() # сохраняем html в виде объекта BeautifulSoup soup = BeautifulSoup(content, "lxml") # Находим все теги "a" с классом "post__title_link" all_a_titles = soup.findAll("a", < "class" : "post__title_link" >) # Проходим по каждому найденному тегу и выводим на экран название статьи for a_title in all_a_titles: print(a_title.text)
Шаг #3 requirements.txt.
Если вы просматривали какие-либо проекты Python на Github или где-либо еще, вы, вероятно, заметили файл под названием requirements.txt . Этот файл используется для указания того, какие пакеты необходимы для запуска проекта (в нашем случае beautifulsoup4 и lxml).
Файл requirements.txt создается командой:
pip freeze > requirements.txt
и выглядит следующим образом:
beautifulsoup4==4.8.2 lxml==4.4.2 soupsieve==1.9.5
Теперь ваш скрипт вместе с файлом requirements.txt можно сохранить в системе контроля версий (например git).
Для работы парсера в новом месте (например на компьютере другого разработчика или на удаленном сервере) необходимо затянуть файлы из системы контроля версий и выполнить команду:
pip install -r requirements.txt
Шаг #4 Обновление/удаление установленных пакетов.
Команда pip list —outdated выведет список всех устаревших пакетов. Обновить отдельно выбранный пакет поможет команда:
pip install package-name —upgrade
Однако бывают ситуации, когда нужно обновить сразу все пакеты из requirements.txt. Достаточно выполнить команду:
pip install -r requirements.txt —upgrade
Для удаления пакета выполните:
pip uninstall package-name
Для удаления всех пакетов из requirements.txt:
pip uninstall -r requirements.txt -y
Мы разобрали основы по работе с PIP. Как правило, этого достаточно для работы с большей частью проектов.
Installing packages using pip and virtual environments¶
This guide discusses how to install packages using pip and a virtual environment manager: either venv for Python 3 or virtualenv for Python 2. These are the lowest-level tools for managing Python packages and are recommended if higher-level tools do not suit your needs.
This doc uses the term package to refer to a Distribution Package which is different from an Import Package that which is used to import modules in your Python source code.
Installing pip¶
pip is the reference Python package manager. It’s used to install and update packages. You’ll need to make sure you have the latest version of pip installed.
Debian and most other distributions include a python-pip package; if you want to use the Linux distribution-provided versions of pip, see Installing pip/setuptools/wheel with Linux Package Managers .
You can also install pip yourself to ensure you have the latest version. It’s recommended to use the system pip to bootstrap a user installation of pip:
Afterwards, you should have the latest version of pip installed in your user site:
The Python installers for Windows include pip. You can make sure that pip is up-to-date by running:
Afterwards, you should have the latest version of pip:
Installing virtualenv¶
If you are using Python 3.3 or newer, the venv module is the preferred way to create and manage virtual environments. venv is included in the Python standard library and requires no additional installation. If you are using venv, you may skip this section.
virtualenv is used to manage Python packages for different projects. Using virtualenv allows you to avoid installing Python packages globally which could break system tools or other projects. You can install virtualenv using pip.
Creating a virtual environment¶
venv (for Python 3) and virtualenv (for Python 2) allow you to manage separate package installations for different projects. They essentially allow you to create a “virtual” isolated Python installation and install packages into that virtual installation. When you switch projects, you can simply create a new virtual environment and not have to worry about breaking the packages installed in the other environments. It is always recommended to use a virtual environment while developing Python applications.
To create a virtual environment, go to your project’s directory and run venv. If you are using Python 2, replace venv with virtualenv in the below commands.
The second argument is the location to create the virtual environment. Generally, you can just create this in your project and call it env .
venv will create a virtual Python installation in the env folder.
You should exclude your virtual environment directory from your version control system using .gitignore or similar.
Activating a virtual environment¶
Before you can start installing or using packages in your virtual environment you’ll need to activate it. Activating a virtual environment will put the virtual environment-specific python and pip executables into your shell’s PATH .
You can confirm you’re in the virtual environment by checking the location of your Python interpreter: