Pip — менеджер пакетов для Python, работа с ним осуществляется через командную строку. Pip не нужно устанавливать отдельно, если вы пользуетесь Python версии 2.7.9 и новее или версии 3.4 и новее. Если pip установлен, то можно ввести в командную строку:
Команды статье указаны для Windows, работа с pip в Linux может отличаться.
Вы получите справку по основным командам.
Если pip не установлен, то нужно скачать скрипт. Выбирайте папку с номером вашей версии Python. После этого в командной строке перейдите в папку со скриптом и выполните команду:
Если pip установлен в папку ProgramFiles, то вам нужно запускать командную строку от администратора.
Если вы установили pip, но все равно получаете ошибку в консоли, нужно указать путь к файлу pip.exe в переменной Path. Для этого зайдите в свойства компьютера>Дополнительные параметры системы>Переменные среды. Здесь (в зависимости о версии Windows) либо добавьте путь к уже существующему через точку с запятой, либо просто нажмите создать и скопируйте путь в новое поле.
Если вам нужно обновить pip напишите в командной строке:
python -m pip install --upgrade pip
Управление пакетами
Чтобы выполнить установку пакета с сайта pypi.org введите в консоли:
python -m pip install ИмяПакета
Если вам нужно использовать несколько версий pip, то нужную можно указать так (начиная с версии pip 0.8):
pip-0.8 install ИмяПакета
Таким же образом можно выбирать версию Python:
python-3.6 -m pip install ИмяПакета
Pip версии 1.5 и выше следует указывать так:
Чтобы обновить пакет введите:
python -m pip install --upgrade ИмяПакета
Для удаления пакета используйте команду uninstall:
python -m pip uninstall ИмяПакета
Флаг -m используется для того чтобы запустить установленный модуль, как скрипт (если написать pip без -m вы можете получить ошибку).
Вывести список всех установленных пакетов в файл можно с помощью :
pip freeze > requirements.txt // название файла может быть любым
При наличии такого файла, можно устанавливать пакеты группами:
pip install -r requirements.txt// версии пакетов в файле указывать не обязательно
Необходимые пакеты можно найти не заходя на сайт pyPi.org (в данный момент недоступно):
pip search строка для поиска
Чтобы узнать подробности об установленном пакете введите:
Проверить установлены ли все зависимости для ваших пакетов можно так:
Теперь, с этими знаниями, вы можете самостоятельно скачать пакет cowsay, зайти в python, и ввести этот текст:
>>> import cowsay
>>> cowsay.cow('Я умею работать с pip! Му!')
Готово! У вас есть говорящая консольная корова:
В статье рассказывается:
В статье рассказывается:
- Установка PIP для Python 3 и 2
- Установка пакета в pip
- Удаление пакета Python
- Как установить пакеты в Python без pip
-
Пройди тест и узнай, какая сфера тебе подходит:
айти, дизайн или маркетинг.Бесплатно от Geekbrains
Прежде чем что-то устанавливать, давайте разберёмся, что такое пакет, чем он отличается от модуля, и как с ним работать. У слова «пакет» применительно к Python два значения.
C одной стороны, пакеты Python — это Py-приложения, дополнения или утилиты, которые можно установить из внешнего репозитория: Github, Bitbucket, Google Code или официального Python Package Index. На сервере пакеты хранятся в .zip и .tar архивах, либо в дополнительной упаковке — «яйцах» (.egg, старый формат) или «колесах» (.whl). В составе пакета, как правило, есть сценарий установки setup.py, который хранит сведения о зависимостях — других пакетах и модулях, без которых пакет работать не будет.
С другой стороны, если речь об архитектуре Python-приложения, пакет — это каталог, внутри которого файл __init__.py и, опционально, другие каталоги и файлы .py. Так большую Python-программу разбивают на пакеты и модули. Модуль — файл с исходным кодом, который можно использовать в других приложениях: как «заготовку» для будущих проектов или как часть библиотеки/фреймворка. Но к теме статьи это прямого отношения не имеет, поэтому дальше мы будем говорить только о пакетах из репозиториев.
Чтобы за секунды устанавливать пакеты со всеми зависимостями, используют менеджер пакетов pip или модуль easy_install. В большинстве случаев рекомендуется использовать pip. И только если у вас есть инфраструктура на пакетах .egg, которые pip не открывает, нужен easy_install.
Если вы используете виртуальные окружения на базе venv или virtualenv, pip уже установлен. Начиная с Python 3.4 (для Python 2 — с версии 2.7.9) pip поставляется вместе с интерпретатором. Для более ранних версий устанавливать менеджер пакетов нужно вручную. Вариантов два:
- C помощью скрипта get_pip.py — быстро.
- Через setuptools — кроме pip сможем использовать easy_install.
Читайте также!
Типы данных в Python – особенности разработки
Вариант 1. Скачиваем скрипт get_pip.py и запускаем в консоли. Для этого открываем терминал через Win+R>»cmd»>OK и пишем:
python get_pip.py
Остальное установщик сделает сам: если нужно, попутно установит wheel (для распаковки .whl-колес) и setuptools. Чтобы запретить инсталляцию дополнительных инструментов, можно добавить в строку ключи —no-setuptools и/или —no-wheels.
Топ-30 самых востребованных и высокооплачиваемых профессий 2023
Поможет разобраться в актуальной ситуации на рынке труда
Подборка 50+ бесплатных нейросетей для упрощения работы и увеличения заработка
Только проверенные нейросети с доступом из России и свободным использованием
ТОП-100 площадок для поиска работы от GeekBrains
Список проверенных ресурсов реальных вакансий с доходом от 210 000 ₽
Уже скачали 34216
Если возникает ошибка, путь к Python не прописан в переменной среды $PATH. Нужно либо найти эту переменную в системном реестре и задать её значение, либо каждый раз указывать полный путь до python.exe, а за ним уже имя исполняемого Py-файла:
C:/python32/python.exe get_pip.py
Полный путь полезен и в том случае, если у вас на компьютере несколько версий Python и вы ставите пакет для одной из них.
Вариант 2. Скачиваем архив с setuptools из PYPI и распаковываем в отдельный каталог. В терминале переходим в директорию setuptools c файлом setup.py и пишем:
python setup.py install
Обновить pip для Python в Windows можно так:python pip install -U pip
Если это не работает, нужно добавить путь к папке с pip в $PATH.
Только до 15.05
Скачай подборку материалов, чтобы гарантированно найти работу в IT за 14 дней
Список документов:
ТОП-100 площадок для поиска работы от GeekBrains
20 профессий 2023 года, с доходом от 150 000 рублей
Чек-лист «Как успешно пройти собеседование»
Чтобы получить файл, укажите e-mail:
Введите e-mail, чтобы получить доступ к документам
Подтвердите, что вы не робот,
указав номер телефона:
Введите телефон, чтобы получить доступ к документам
Уже скачали 52300
Установка пакета в pip
Пора запустить pip в Python и начать устанавливать пакеты короткой командой из консоли:
pip install имя_пакета
При установке в Windows, перед pip нужно добавить «python -m».
Обновить пакет не сложнее:
pip install имя_пакета -U
Если у вас последняя версия пакета, но вы хотите принудительно переустановить его:
pip install --force-reinstall
Посмотреть список установленных пакетов Python можно с помощью команды:
pip list
Найти конкретный пакет по имени можно командой «pip search». О других командах можно прочесть в справке, которая выдается по команде «pip help».
Удаление пакета Python
Когда пакет больше не нужен, пишем:
pip uninstall имя_пакета
Как установить пакеты в Python без pip
Формат .egg сейчас используют не часто, поэтому pip его не поддерживает. Модуль easy_install умеет устанавливать как .egg, так и обычные пакеты, но есть у него важные минусы:
- он не удаляет пакеты,
- он может пытаться установить недозагруженный пакет.
Использовать easy_install можно сразу после установки setuptools. Хранится модуль в папке Scripts вашего интерпретатора. Если у вас в $PATH верно прописан путь, ставить пакеты из PYPI можно короткой командой:
easy_install имя_пакета
Для обновления после install и перед именем пакета нужно ставить ключ -U. Откатиться до нужной версии можно так:
easy_install имя_пакета=0.2.3
Если нужно скачать пакет из альтернативного источника, вы можете задать URL или локальный адрес на компьютере:
easy_install http://адрес_репозитория.ру/директория/пакет-1.1.2.zip
Чтобы узнать об опциях easy_install, запустим его с ключом -h:
easy_install -h
Список пакетов, установленных через easy_install, хранится в файле easy-install.pth в директории /libs/site-packages/ вашего Python.
Дарим скидку от 60%
на обучение «Python-разработчик» до 18 мая
Уже через 9 месяцев сможете устроиться на работу с доходом от 150 000 рублей
Забронировать скидку
К счастью, удалять установленные через easy_install пакеты можно с помощью pip. Если же его нет, потребуется удалить пакет вручную и стереть сведения о нем из easy-install.pth.
Теперь вы умеете ставить и удалять пакеты для вашей версии Python.
PIP stands for “Preferred Installer Program” or “Pip Installs Packages” and is a standard package manager for Python that enables users to install and manage additional libraries and dependencies not included in the standard Python library. To use PIP, you must install Python on your Windows machine.
This article provides a step-by-step guide on how to install and configure PIP on Windows, along with tips for managing Python packages effectively.
Prerequisities:
- Windows (11, 10, 8 , 7)
- Python (version 3.13.1)
- Admin Rights
Verify Python Installation
Before installing PIP, you need to ensure that Python is already installed on your system. You can check this by running the following command in the command prompt
python --version
If it is installed, You will see something like this:
Python 3.13.1
If it is not installed, you can install it with the help of this article: How to install Python on Windows.
To get more knowledge about Python packages or modules, get hands-on in our Python course. This course will offer you basic to advanced insights into Python programming.
Installing Python PIP on Windows
Installing pip in Windows is very easy. You just need to follow the given steps to install pip and some additional steps to finally use it. By these steps, we can see how to pip install on Windows. To ensure proper installation and use of pip we need to tick this checklist to install pip Python:
- Download PIP
- Install PIP
- Verify Installation
- Add pip to environment variables
1. Download PIP
To install PIP, you’ll need the get-pip.py script. Let’s understand this in the below-mentioned detailed steps:
Method 1. Install Python pip using Python cURL
Curl is a UNIX command that is used to send the PUT, GET, and POST requests to a URL. This tool is utilized for downloading files, testing REST APIs, etc.
Note: It will download the get-pip.py file.
Follow these instructions to pip windows install:
Step 1: Open Command Prompt
Press Win + R and type CMD and hit the enter button to open the cmd terminal using the Windows keyboard shortcut or alternatively, click on Start Menu and type “Command Prompt” and hit the enter button.
Start Menu – Command Prompt – Run as admin
2. Installing PIP
Here, we have now used cURL to transfer the data requests, let’s check out the executed command in here:
Step 2: Transfer Data Request from a Server
In python, a curl is a tool for transferring data requests to and from a server. Use the following command to request:
https://bootstrap.pypa.io/get-pip.py
python get-pip.py
Method 2. Manually Download and Install Python PIP on Windows
Python pip must be manually installed on Windows. We can pip install in Python by manually installing it. You might need to use the correct version of the file from pypa.io if you’re using an earlier version of Python or pip. Get the file and save it to a folder on your PC.
1.1 Download PIP
This is another method for downloading PIP manually. Let’s check down the steps below:
Step 1: Download the get-pip-py Script
Download the get-pip.py (https://bootstrap.pypa.io/get-pip.py) file and store it in the same directory as Python is installed.
Step 2: Change the Directory
Change the current path of the directory in the command line to the path of the directory where the above file exists.
2.2 Installing PIP
Now, in the next two steps, we will understand how you can install PIP in Python environment. Let’s check them out:
Step 3: Execute the command to Install Python
get-pip.py is a bootstrapping script that enables users to install pip in Python environments. Here, we are installing pip python3. Run the command given below:
python get-pip.py
Step 4: Wait Untill You Get the Confirmation
Now wait through the installation process. Voila! pip is now installed on your system.
3. Verify the PIP Installation
One can easily verify if the pip has been installed correctly by performing a version check on the same. Just go to the command line and execute the following command:
pip -Vorpip --version
4. Adding PIP to Windows Environment Variables
If you are facing any path error then you can follow the following steps to add the pip to your PATH. You can follow the following steps to adding pip to path Windows 10 and set the Path:
Step 1: Locate te PIP installation directory
- You are likely to get this in: C\Python33\Scripts\
Step 2: Add to the PATH
- Go to System and Security > System in the Control Panel
- On the left side, click the Advanced system settings link.
- Then, select Environment Variables.
- Double-click the PATH variable under System Variables.
- Click New, and add the directory where pip is installed, e.g. C:\Python33\Scripts\ and select OK.
Step 3: Verify
- Open the command prompt and type the following command to verify the PIP installation:
pip --version
How to Upgrade Pip On Windows
pip can be upgraded using the following command:
python -m pip install -U pip
How to Downgrad PIP on Windows
It may happen sometimes that your current pip version is not supporting your current version of python or machine.
To fix that, you can downgrade your pip version with the help of Python pip install command and the following command.
Note: You can mention the version you want to install
python -m pip install pip==17.0
If you followed these steps, you will not face any issues while installing pip on windows. We have also discussed methods to upgrade or downgrade pip version in case you face any issues.
Managing Python Packages with PIP
Once PIP is installed, you can use it to manage Python packages. Here are some common commands:
- Install a Package: To install a package, use:
pip install package_name
- Uninstall a Package: To remove a package, use:
pip uninstall package_name
- List Installed Packages: To see all installed packages, use:
pip list
- Show Package Information: To get detailed information about a package, use:
pip show package_name
- Search for Packages: To search for packages in the Python Package Index (PyPI), use:
pip search package_name
Troubleshooting Tips
1. Python Not Recognized
Always ensure that Python is added to the PATH during the installation. In case, if it’s not, you can modify the PATH manually.
2. Permission Errors
Try running the Command Prompt as an administrator access.
3. SSL Errors
Ensure that te date and time is correct of your system (as SSL certificates usually relies on actual system clocks.)
Also Read
- How to install PIP in Linux?
- How to install pip in macOS?
- Download and install pip Latest Version
Conclusion
By following this guide, you can successfully download, install, upgrade, downgrade, and manage PIP on Windows seamlessly. With PIP installed in your system, you can easily manage to Python packages and enhance your Python development environment. Whether you’re a beginner or an experienced developer, understanding how to work with PIP is essential for efficient Python programming.
Чтобы не писать нужные функции с нуля каждый раз, разработчики используют библиотеки. Это наборы готового кода для выполнения какой-то задачи — например, математическая библиотека numpy содержит функции для работы с числами.
Большинство библиотек не подключены к языку программирования по умолчанию. Их нужно загружать отдельно. Разберемся, как сделать это в Python — одном из самых популярных языков программирования.
Способ №1. Установить библиотеку вручную
Большинство пакетов с библиотеками Python собрано на сайте под названием PyPI. На его главной странице есть окно поиска, через которое можно найти интересующий пакет. А затем открыть его страницу и увидеть информацию по нему.
Сайт предлагает скачать и установить любой пакет двумя способами:
- с помощью команды пакетного менеджера pip;
- вручную — для этого нужно скачать архив с библиотекой с сайта PyPI.
После того как файл загрузится на компьютер, его нужно будет разархивировать. А затем — открыть консоль командной строки и перейти в папку, где лежит пакет. Там в терминале нужно будет выполнить команду:
python setup.py install
Эта команда с помощью Python запускает файл setup.py — в пакете он отвечает за установку компонентов.
Если возникает ошибка — скорее всего дело в том, что командная строка не понимает, где находится Python. В таком случае можно прописать полный путь к папке, где находятся файлы языка.
Способ №2. Использовать easy install
Для Python существует модуль под названием easy install. Он позволяет быстро устанавливать в язык новые расширения — понадобится всего лишь написать одну команду. Скачать этот модуль проще всего вместе с расширением setuptools — оно есть на PyPI, и его можно установить вручную способом из предыдущего пункта.
После того как утилита установится, можно будет загрузить библиотеку в Python через нее. Для этого нужно из папки, где установлен setuptools, вызвать в терминале команду:
easy_install <имя пакета>
Вместо <имя пакета> нужно подставить название интересующей библиотеки, которое можно посмотреть на PyPI или ее официальном сайте. Инструмент скачает и установит библиотеку автоматически.
Пользоваться easy install можно и из других папок — но понадобится прописывать полный путь к утилите. Правда, если установить ее в корневой каталог операционной системы, это делать не понадобится — ОС будет «видеть» утилиту, из какой бы папки ее ни вызвали.
У easy install есть два ограничения:
- с ее помощью нельзя удалить какую-то библиотеку или отключить ее;
- иногда при использовании возникают ошибки — она может попытаться запустить не установленную на компьютер библиотеку.
Способ №3. Использовать pip
Это самый популярный способ установки библиотек в Python. Для языка существует менеджер пакетов под названием pip. С его помощью устанавливать новые компоненты можно буквально с помощью одной команды.
Начиная с Python версии 3.4 pip устанавливается вместе с самим языком. Его не нужно скачивать отдельно. Это понадобится, только если вы работаете с какой-то из более старых версий.
Проверить, установлен ли pip, можно с помощью команды в терминале:
pip --version
Если менеджер уже установлен, высветится его версия. Если нет — появится сообщение, что такого пакета в системе нет. В таком случае pip можно скачать с PyPI и установить ручным способом.
Также pip можно загрузить с сайта PyPa — рабочей группы, которая занимается его разработкой. Вручную это можно сделать в любой системе. В Linux также возможно скачать его с помощью команды в терминале:
wget https://bootstrap.pypa.io/get-pip.py
Или с помощью easy install:
easy_install pip
Оба способа позволяют скачать файл get-pip.py. После этого его нужно запустить в Python через терминал:
python get-pip.py
После того как pip загрузится и инсталлируется, его можно будет использовать для установки библиотек. Это просто — фактически установить нужный пакет можно с помощью одной команды. Но возможности pip куда шире, чем у easy install.
Менеджер умеет не только устанавливать, но и обновлять или удалять библиотеки в Python. А еще — подгружать зависимости, то есть модули, нужные для работы какой-то из библиотек.
Установить модуль в Python с помощью pip можно так:
pip install <имя пакета>
Кроме того, есть еще несколько команд, которые могут понадобиться при работе с библиотеками:
- pip install -U <имя пакета> — обновить библиотеку до актуальной версии;
- pip install <имя пакета>==<номер версии> — установить библиотеку какой-то конкретной версии;
- pip install —force-reinstall <имя пакета> — принудительно переустановить библиотеку, например если та установилась с ошибками;
- pip uninstall <имя пакета> — удалить библиотеку, которая перестала быть нужной;
- pip list — посмотреть список установленных пакетов;
- pip show <имя пакета> — посмотреть информацию о конкретном установленном пакете.
Достаточно ввести нужную команду в терминал, и pip автоматически выполнит нужное действие.
Что еще стоит сделать
Каким бы способом вы ни пользовались, после установки нужно проверить, точно ли пакет работает нормально. Для этого достаточно подключить библиотеку к Python-коду и попробовать ее использовать.
Чтобы конкретная программа «увидела» нужный модуль, его нужно добавить в код с помощью строчки:
import <имя пакета>
Обычно модули подключают в самом начале файла с кодом. То есть, первые строки программы — добавление библиотек, нужных для ее работы.
После этого можно использовать в коде нужные функции и компоненты из библиотеки. Если все установилось как следует, при этом не должно возникнуть никаких ошибок. Готово — нужными модулями можно пользоваться на свое усмотрение.
Usage¶
Unix/macOS
python -m pip install [options] <requirement specifier> [package-index-options] ... python -m pip install [options] -r <requirements file> [package-index-options] ... python -m pip install [options] [-e] <vcs project url> ... python -m pip install [options] [-e] <local project path> ... python -m pip install [options] <archive url/path> ...
Windows
py -m pip install [options] <requirement specifier> [package-index-options] ... py -m pip install [options] -r <requirements file> [package-index-options] ... py -m pip install [options] [-e] <vcs project url> ... py -m pip install [options] [-e] <local project path> ... py -m pip install [options] <archive url/path> ...
Description¶
Install packages from:
-
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
pyproject.toml
orsetup.py
,
otherwise pip will report an error). -
Local file (a sdist or wheel format archive, following the naming
conventions for those formats). -
A version specifier.
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¶
Note
This section is only about installation order of runtime dependencies, and
does not apply to build dependencies (those are specified using the
[build-system] table).
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:
Unix/macOS
$ python -m pip install quux ... Installing collected packages baz, bar, foo, quux $ python -m pip install bar ... Installing collected packages foo, baz, bar
Windows
C:\> py -m pip install quux ... Installing collected packages baz, bar, foo, quux C:\> py -m pip install bar ... Installing collected packages foo, baz, bar
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
usinginstall_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.
Requirement Specifiers
This section has been moved to Requirement Specifiers.
Per-requirement Overrides
This is now covered in Requirements File Format.
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 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.
VCS Support
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 (or the index given as
--index-url
, if not disabled via --no-index
), in the local filesystem,
and in any additional repositories specified via --find-links
or
--extra-index-url
. There is no priority in the locations that are searched.
Rather they are all checked, and the “best” match for the requirements (in
terms of version number — see the
specification for details) is selected.
See the pip install Examples.
SSL Certificate Verification
This is now covered in HTTPS Certificates.
Caching
This is now covered in Caching.
Wheel Cache
This is now covered in Caching.
Hash checking mode
This is now covered in Secure installs.
Local Project Installs
This is now covered in Local project installs.
Editable installs
This is now covered in Local project installs.
Build System Interface
This is now covered in Build System Interface.
Options¶
- -r, —requirement <file>¶
-
Install from the given requirements file. This option can be used multiple times.
(environment variable:
PIP_REQUIREMENT
)
- -c, —constraint <file>¶
-
Constrain versions using the given constraints file. This option can be used multiple times.
(environment variable:
PIP_CONSTRAINT
)
- —no-deps¶
-
Don’t install package dependencies.
(environment variable:
PIP_NO_DEPS
,PIP_NO_DEPENDENCIES
)
- —pre¶
-
Include pre-release and development versions. By default, pip only finds stable versions.
(environment variable:
PIP_PRE
)
- -e, —editable <path/url>¶
-
Install a project in editable mode (i.e. setuptools “develop mode”) from a local project path or a VCS url.
(environment variable:
PIP_EDITABLE
)
- —dry-run¶
-
Don’t actually install anything, just print what would be. Can be used in combination with —ignore-installed to ‘resolve’ the requirements.
(environment variable:
PIP_DRY_RUN
)
- -t, —target <dir>¶
-
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.
(environment variable:
PIP_TARGET
)
- —platform <platform>¶
-
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.
(environment variable:
PIP_PLATFORM
)
- —python-version <python_version>¶
-
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).(environment variable:
PIP_PYTHON_VERSION
)
- —implementation <implementation>¶
-
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.
(environment variable:
PIP_IMPLEMENTATION
)
- —abi <abi>¶
-
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.
(environment variable:
PIP_ABI
)
- —user¶
-
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.)
(environment variable:
PIP_USER
)
- —root <dir>¶
-
Install everything relative to this alternate root directory.
(environment variable:
PIP_ROOT
)
- —prefix <dir>¶
-
Installation prefix where lib, bin and other top-level folders are placed. Note that the resulting installation may contain scripts and other resources which reference the Python interpreter of pip, and not that of
--prefix
. See also the--python
option if the intention is to install packages into another (possibly pip-free) environment.(environment variable:
PIP_PREFIX
)
- —src <dir>¶
-
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”.
(environment variable:
PIP_SRC
,PIP_SOURCE
,PIP_SOURCE_DIR
,PIP_SOURCE_DIRECTORY
)
- -U, —upgrade¶
-
Upgrade all specified packages to the newest available version. The handling of dependencies depends on the upgrade-strategy used.
(environment variable:
PIP_UPGRADE
)
- —upgrade-strategy <upgrade_strategy>¶
-
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).
(environment variable:
PIP_UPGRADE_STRATEGY
)
- —force-reinstall¶
-
Reinstall all packages even if they are already up-to-date.
(environment variable:
PIP_FORCE_REINSTALL
)
- -I, —ignore-installed¶
-
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!
(environment variable:
PIP_IGNORE_INSTALLED
)
- —ignore-requires-python¶
-
Ignore the Requires-Python information.
(environment variable:
PIP_IGNORE_REQUIRES_PYTHON
)
- —no-build-isolation¶
-
Disable isolation when building a modern source distribution. Build dependencies specified by PEP 518 must be already installed if this option is used.
(environment variable:
PIP_NO_BUILD_ISOLATION
)
- —use-pep517¶
-
Use PEP 517 for building source distributions (use —no-use-pep517 to force legacy behaviour).
(environment variable:
PIP_USE_PEP517
)
- —check-build-dependencies¶
-
Check the build dependencies when PEP517 is used.
(environment variable:
PIP_CHECK_BUILD_DEPENDENCIES
)
- —break-system-packages¶
-
Allow pip to modify an EXTERNALLY-MANAGED Python installation
(environment variable:
PIP_BREAK_SYSTEM_PACKAGES
)
- -C, —config-settings <settings>¶
-
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.
(environment variable:
PIP_CONFIG_SETTINGS
)
- —global-option <options>¶
-
Extra global options to be supplied to the setup.py call before the install or bdist_wheel command.
(environment variable:
PIP_GLOBAL_OPTION
)
- —compile¶
-
Compile Python source files to bytecode
(environment variable:
PIP_COMPILE
)
- —no-compile¶
-
Do not compile Python source files to bytecode
(environment variable:
PIP_NO_COMPILE
)
- —no-warn-script-location¶
-
Do not warn when installing scripts outside PATH
(environment variable:
PIP_NO_WARN_SCRIPT_LOCATION
)
- —no-warn-conflicts¶
-
Do not warn about broken dependencies
(environment variable:
PIP_NO_WARN_CONFLICTS
)
- —no-binary <format_control>¶
-
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.
(environment variable:
PIP_NO_BINARY
)
- —only-binary <format_control>¶
-
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.
(environment variable:
PIP_ONLY_BINARY
)
- —prefer-binary¶
-
Prefer binary packages over source packages, even if the source packages are newer.
(environment variable:
PIP_PREFER_BINARY
)
- —require-hashes¶
-
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.
(environment variable:
PIP_REQUIRE_HASHES
)
- —progress-bar <progress_bar>¶
-
Specify whether the progress bar should be used [on, off, raw] (default: on)
(environment variable:
PIP_PROGRESS_BAR
)
- —root-user-action <root_user_action>¶
-
Action if pip is run as a root user [warn, ignore] (default: warn)
(environment variable:
PIP_ROOT_USER_ACTION
)
- —report <file>¶
-
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.
(environment variable:
PIP_REPORT
)
- —group <[path:]group>¶
-
Install a named dependency-group from a “pyproject.toml” file. If a path is given, the name of the file must be “pyproject.toml”. Defaults to using “pyproject.toml” in the current directory.
(environment variable:
PIP_GROUP
)
- —no-clean¶
-
Don’t clean up build directories.
(environment variable:
PIP_NO_CLEAN
)
- -i, —index-url <url>¶
-
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.
(environment variable:
PIP_INDEX_URL
,PIP_PYPI_URL
)
-
Extra URLs of package indexes to use in addition to —index-url. Should follow the same rules as —index-url.
(environment variable:
PIP_EXTRA_INDEX_URL
)
- —no-index¶
-
Ignore package index (only looking at —find-links URLs instead).
(environment variable:
PIP_NO_INDEX
)
- -f, —find-links <url>¶
-
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.
(environment variable:
PIP_FIND_LINKS
)
Examples¶
-
Install
SomePackage
and its dependencies from PyPI using Requirement SpecifiersUnix/macOS
python -m pip install SomePackage # latest version python -m pip install 'SomePackage==1.0.4' # specific version python -m pip install 'SomePackage>=1.0.4' # minimum version
Windows
py -m pip install SomePackage # latest version py -m pip install "SomePackage==1.0.4" # specific version py -m pip install "SomePackage>=1.0.4" # minimum version
-
Install a list of requirements specified in a file. See the Requirements files.
Unix/macOS
python -m pip install -r requirements.txt
Windows
py -m pip install -r requirements.txt
-
Upgrade an already installed
SomePackage
to the latest from PyPI.Unix/macOS
python -m pip install --upgrade SomePackage
Windows
py -m pip install --upgrade SomePackage
Note
This will guarantee an update to
SomePackage
as it is a direct
requirement, and possibly upgrade dependencies if their installed
versions do not meet the minimum requirements ofSomePackage
.
Any non-requisite updates of its dependencies (indirect requirements)
will be affected by the--upgrade-strategy
command. -
Install a local project in “editable” mode. See the section on Editable Installs.
Unix/macOS
python -m pip install -e . # project in current directory python -m pip install -e path/to/project # project in another directory
Windows
py -m pip install -e . # project in current directory py -m pip install -e path/to/project # project in another directory
-
Install a project from VCS
Unix/macOS
python -m pip install 'SomeProject@git+https://git.repo/some_pkg.git@1.3.1'
Windows
py -m pip install "SomeProject@git+https://git.repo/some_pkg.git@1.3.1"
-
Install a project from VCS in “editable” mode. See the sections on VCS Support and Editable Installs.
Unix/macOS
python -m pip install -e 'git+https://git.repo/some_pkg.git#egg=SomePackage' # from git python -m pip install -e 'hg+https://hg.repo/some_pkg.git#egg=SomePackage' # from mercurial python -m pip install -e 'svn+svn://svn.repo/some_pkg/trunk/#egg=SomePackage' # from svn python -m pip install -e 'git+https://git.repo/some_pkg.git@feature#egg=SomePackage' # from 'feature' branch python -m pip install -e 'git+https://git.repo/some_repo.git#egg=subdir&subdirectory=subdir_path' # install a python package from a repo subdirectory
Windows
py -m pip install -e "git+https://git.repo/some_pkg.git#egg=SomePackage" # from git py -m pip install -e "hg+https://hg.repo/some_pkg.git#egg=SomePackage" # from mercurial py -m pip install -e "svn+svn://svn.repo/some_pkg/trunk/#egg=SomePackage" # from svn py -m pip install -e "git+https://git.repo/some_pkg.git@feature#egg=SomePackage" # from 'feature' branch py -m pip install -e "git+https://git.repo/some_repo.git#egg=subdir&subdirectory=subdir_path" # install a python package from a repo subdirectory
-
Install a package with extras, i.e., optional dependencies
(specification).Unix/macOS
python -m pip install 'SomePackage[PDF]' python -m pip install 'SomePackage[PDF] @ git+https://git.repo/SomePackage@main#subdirectory=subdir_path' python -m pip install '.[PDF]' # project in current directory python -m pip install 'SomePackage[PDF]==3.0' python -m pip install 'SomePackage[PDF,EPUB]' # multiple extras
Windows
py -m pip install "SomePackage[PDF]" py -m pip install "SomePackage[PDF] @ git+https://git.repo/SomePackage@main#subdirectory=subdir_path" py -m pip install ".[PDF]" # project in current directory py -m pip install "SomePackage[PDF]==3.0" py -m pip install "SomePackage[PDF,EPUB]" # multiple extras
-
Install a particular source archive file.
Unix/macOS
python -m pip install './downloads/SomePackage-1.0.4.tar.gz' python -m pip install 'http://my.package.repo/SomePackage-1.0.4.zip'
Windows
py -m pip install "./downloads/SomePackage-1.0.4.tar.gz" py -m pip install "http://my.package.repo/SomePackage-1.0.4.zip"
-
Install a particular source archive file following direct references
(specification).Unix/macOS
python -m pip install 'SomeProject@http://my.package.repo/SomeProject-1.2.3-py33-none-any.whl' python -m pip install 'SomeProject @ http://my.package.repo/SomeProject-1.2.3-py33-none-any.whl' python -m pip install 'SomeProject@http://my.package.repo/1.2.3.tar.gz'
Windows
py -m pip install "SomeProject@http://my.package.repo/SomeProject-1.2.3-py33-none-any.whl" py -m pip install "SomeProject @ http://my.package.repo/SomeProject-1.2.3-py33-none-any.whl" py -m pip install "SomeProject@http://my.package.repo/1.2.3.tar.gz"
-
Install from alternative package repositories.
Install from a different index, and not PyPI
Unix/macOS
python -m pip install --index-url http://my.package.repo/simple/ SomePackage
Windows
py -m pip install --index-url http://my.package.repo/simple/ SomePackage
Install from a local flat directory containing archives (and don’t scan indexes):
Unix/macOS
python -m pip install --no-index --find-links=file:///local/dir/ SomePackage python -m pip install --no-index --find-links=/local/dir/ SomePackage python -m pip install --no-index --find-links=relative/dir/ SomePackage
Windows
py -m pip install --no-index --find-links=file:///local/dir/ SomePackage py -m pip install --no-index --find-links=/local/dir/ SomePackage py -m pip install --no-index --find-links=relative/dir/ SomePackage
Search an additional index during install, in addition to PyPI
Warning
Using this option to search for packages which are not in the main
repository (such as private packages) is unsafe, per a security
vulnerability called
dependency confusion:
an attacker can claim the package on the public repository in a way that
will ensure it gets chosen over the private package.Unix/macOS
python -m pip install --extra-index-url http://my.package.repo/simple SomePackage
Windows
py -m pip install --extra-index-url http://my.package.repo/simple SomePackage
-
Find pre-release and development versions, in addition to stable versions. By default, pip only finds stable versions.
Unix/macOS
python -m pip install --pre SomePackage
Windows
py -m pip install --pre SomePackage
-
Install packages from source.
Do not use any binary packages
Unix/macOS
python -m pip install SomePackage1 SomePackage2 --no-binary :all:
Windows
py -m pip install SomePackage1 SomePackage2 --no-binary :all:
Specify
SomePackage1
to be installed from source:Unix/macOS
python -m pip install SomePackage1 SomePackage2 --no-binary SomePackage1
Windows
py -m pip install SomePackage1 SomePackage2 --no-binary SomePackage1