View this page
Toggle table of contents sidebar
Usually, pip is automatically installed if you are:
-
working in a
virtual environment -
using Python downloaded from python.org
-
using Python that has not been modified by a redistributor to remove
ensurepip
Supported Methods¶
If your Python environment does not have pip installed, there are 2 mechanisms
to install pip supported directly by pip’s maintainers:
-
ensurepip
-
get-pip.py
ensurepip
¶
Python comes with an ensurepip
module[1], which can install pip in
a Python environment.
Linux
$ python -m ensurepip --upgrade
MacOS
$ python -m ensurepip --upgrade
Windows
C:> py -m ensurepip --upgrade
More details about how ensurepip
works and how it can be used, is
available in the standard library documentation.
get-pip.py
¶
This is a Python script that uses some bootstrapping logic to install
pip.
-
Download the script, from https://bootstrap.pypa.io/get-pip.py.
-
Open a terminal/command prompt,
cd
to the folder containing the
get-pip.py
file and run:
More details about this script can be found in pypa/get-pip’s README.
Standalone zip application¶
Note
The zip application is currently experimental. We test that pip runs correctly
in this form, but it is possible that there could be issues in some situations.
We will accept bug reports in such cases, but for now the zip application should
not be used in production environments.
In addition to installing pip in your environment, pip is available as a
standalone zip application.
This can be downloaded from https://bootstrap.pypa.io/pip/pip.pyz. There are
also zip applications for specific pip versions, named pip-X.Y.Z.pyz
.
The zip application can be run using any supported version of Python:
If run directly:
Linux
$ chmod +x ./pip.pyz $ ./pip.pyz
then the currently active Python interpreter will be used.
MacOS
$ chmod +x ./pip.pyz $ ./pip.pyz
then the currently active Python interpreter will be used.
Windows
then the currently active Python interpreter will be used.
You may need to configure your system to recognise the .pyz
extension
before this will work.
Alternative Methods¶
Depending on how you installed Python, there might be other mechanisms
available to you for installing pip such as
using Linux package managers.
These mechanisms are provided by redistributors of pip, who may have modified
pip to change its behaviour. This has been a frequent source of user confusion,
since it causes a mismatch between documented behaviour in this documentation
and how pip works after those modifications.
If you face issues when using Python and pip installed using these mechanisms,
it is recommended to request for support from the relevant provider (eg: Linux
distro community, cloud provider support channels, etc).
Upgrading pip
¶
Upgrade your pip
by running:
Linux
$ python -m pip install --upgrade pip
MacOS
$ python -m pip install --upgrade pip
Windows
C:> py -m pip install --upgrade pip
Compatibility¶
The current version of pip works on:
-
Windows, Linux and macOS.
-
CPython 3.9, 3.10, 3.11, 3.12, 3.13, and latest PyPy3.
pip is tested to work on the latest patch version of the Python interpreter,
for each of the minor versions listed above. Previous patch versions are
supported on a best effort approach.
Other operating systems and Python versions are not supported by pip’s
maintainers.
Users who are on unsupported platforms should be aware that if they hit issues, they may have to resolve them for themselves. If they received pip from a source which provides support for their platform, they should request pip support from that source.
В этой статье в очередной раз коснёмся темы установки PIP на Python. Вы узнаете, что делать, если PIP не установлена, как поставить эту систему, а также как выполняется инсталляция на Windows, Mac, Linux и Raspberry Pi. Дополнительно будут рассмотрены вопросы обновления и работы.
Python, как и любой другой серьёзный язык программирования, поддерживает дополнительные (сторонние) фреймворки и библиотеки. Эти библиотеки устанавливаются разработчиками с простой целью: облегчить себе жизнь и каждый раз не изобретать колесо в новом проекте. Нужные пакеты находятся в PyPI, который можно назвать центральным репозиторием Python и каталогом Python-пакетов (Python Package Index).
Но скачивать и устанавливать эти пакеты вручную — занятие утомительное, а порой и времязатратное. Лучше всего использовать для этих целей специальный инструмент для Python, делающий процесс проще и быстрее. Как вы уже догадались, речь идёт про PIP. И если PIP не установлен, обязательно восполните этот пробел.
Что же такое PIP?
Сама аббревиатура PIP («пип») представляет собой рекурсивный акроним. По сути, это система управления пакетами. Она применяется в целях установки и управления программными пакетами, которые написаны на Python. Ещё систему называют предпочитаемым установщиком программ. А непосредственно pip — это команда, запускающая соответствующую утилиту для установки, переустановки и деинсталляции пакетов, которые находятся в вышеупомянутом PyPI.
Часто возникает вопрос, а не устанавливается ли PIP одновременно с Пайтоном? Да, если речь идёт о следующих версиях:
— Python версии 2.7.9 и выше;
— Python версии 3.4 и выше.
В вышеупомянутых случаях «пип» устанавливается по дефолту и вместе с Python. Но если же речь идёт о более старых версиях, PIP не установлена. Однако установить PIP совсем несложно. Но прежде чем это сделать, рекомендуется проверить свою версию Python, а также то, правильно ли он у вас инсталлирован.
Проверка версии Python
Для выполнения проверки Python следует открыть командную строку. Она вам понадобится и при последующих действиях. Следует привыкать работать с командной строкой, т. к. многие операции быстрее, удобнее и нагляднее выполнять именно через неё. Если же вы начинающий системный администратор, знание терминала — это пункт под номером 0 в списке необходимых скиллов.
Запускаем командную строку следующим образом:
1. На Windows. Используем комбинацию клавиш «Win+X».
2. На Mac. Нажимаем «Command+пробел».
3. На Линукс. Работает комбинация «Ctrl+Alt+T».
Когда терминал открыт, вводим следующую команду:
Если у вас Linux и Python 3.x, вводим несколько другую команду:
В итоге вы должны получить актуальную версию Питона, которая установлена на вашу операционную систему. Если же что-то не так, вы получите сообщение, что Пайтон не установлен (Python is not defined).
Устанавливаем PIP на Windows
Инструкции, представленные ниже, подойдут для ОС Windows 7/8.1/10. Общий порядок действий, если PIP не установлен, следующий:
1. Скачиваем официальный установочный скрипт с именем get-pip.py. Для начала нажимаем правую кнопку мыши, потом «Сохранить как…». В итоге скрипт сохранится по указанному вами пути (пусть это будет папка «Загрузки»).
2. Открываем терминал (командную строку), после чего переходим к каталогу, где вы поместили файл get-pip.py.
3. Выполняем команду python get-pip.py.
Всё, установка запустится (installs), и инсталляция модуля будет завершена в сжатые сроки. Способ простой и действенный.
Устанавливаем на Mac
В современных версиях Mac как Python, так и PIP уже установлены. Однако со временем они устаревают, что нехорошо, поэтому лучше следить за тем, чтобы на вашем компьютере были актуальные версии. Но если вы хотите работать с той версией Python, которая есть, и желаете инсталлировать последнюю версию системы, сделать это можно простой командой, запустив в терминале следующее:
Для установки более новых версий языка программирования Python вам пригодится Homebrew. С его помощью Пайтон устанавливается тоже очень просто (предполагается, что утилита командной строки Homebrew уже установлена):
По итогу получите последнюю версию Python, в которую, кстати говоря, система «пип» уже может входить. Но если же пакет будет недоступен, выполните перелинковку:
brew unlink python && brew link pythonУстанавливаем на Linux
Для дистрибутивов Linux желательно использовать системный менеджер пакетов и штатные репозитории. Команды могут различаться с учётом конкретного дистрибутива. Для примера возьмём популярный дистрибутив Ubuntu. Если у вас Python 3, в терминале выполняем:
sudo apt install python3-pipА потом проверяем, что получилось:
Если же речь идёт о Пайтон 2, команды установки и проверки версии будут чуть другими:
sudo apt install python-pipКак установить PIP на Raspberry Pi
Если вы являетесь пользователем Raspberry, эта часть статьи для вас. Если же вы даже не в курсе, что такое Raspberry, можете смело пропустить данный абзац.
Уже начиная с Rapsbian Jessie, система устанавливается по дефолту, то есть вопросов о том, что PIP не установлена, не возникает. Это ещё и причина обновить ОС до Rapsbian Jessie а не использовать Rapsbian Wheezy/Jessie Lite. Однако никто не мешает установить систему и на старую версию.
Для Python 2 это выглядит следующим образом:
sudo apt-get install python-pipДля третьей версии изменения в команде крайне незначительны:
sudo apt-get install python3-pipВ процессе работы нужно будет применять pip и pip3 соответственно.
Обновляем PIP для Python
Для многих разработчиков очень важно иметь последнюю версию установщика программ. Это имеет особое значение, если мы говорим о сохранении приемлемого уровня безопасности, исправлении ошибок (багов) и т. д.
Обновить PIP не составляет труда:
1. Для Windows. Используем команду python -m pip install -U pip.
2. Для Mac, Линукс либо Raspberry Pi — pip install -U pip.Устанавливаем Python-библиотеки посредством PIP
Когда установка (installing) завершена, «пип» установился и готов к работе. В результате мы можем приступать к установке пакетов с помощью PIP из PyPI. Делается это с помощью простейшего синтаксиса, содержащего минимум кода:
По умолчанию с помощью вышеприведённого синтаксиса будет установлена новейшая версия нужного пакета. Но иногда требуется конкретная версия, то есть более старая:
pip install имя_пакаета==1.0.0Также вы можете найти конкретный пакет:
pip search "ваш_запрос_поиска"Или посмотреть детали уже установленного (installed):
Ещё пользователю доступен список всех пакетов, которые установлены:
А также список пакетов PIP, которые устарели:
Но это не беда, ведь можно выполнить обновление:
pip install имя_пакета --upgradeОднако учтите, что при обновлении старая версия будет удалена.
Ещё может возникнуть необходимость в полной переустановке пакета:pip install имя_пакета --upgrade --force-reinstallСовсем несложно и удалить пакет:
Это основы, которые должен знать каждый. Если же вас интересует Python-разработка на более продвинутом уровне, добро пожаловать на курсы в OTUS!
Источники:
• https://pingvinus.ru/note/pip;
• https://pythonru.com/baza-znanij/ustanovka-pip-dlja-python-i-bazovye-komandy.
Как любой серьёзный язык программирования, Python поддерживает сторонние библиотеки и фреймворки. Их устанавливают, чтобы не изобретать колесо в каждом новом проекте. Необходимы пакеты можно найти в центральном репозитории Python — PyPI (Python Package Index — каталог пакетов Python).
Однако скачивание, установка и работа с этими пакетами вручную утомительны и занимают много времени. Именно поэтому многие разработчики полагаются на специальный инструмент PIP для Python, который всё делает гораздо быстрее и проще.
Сама аббревиатура — рекурсивный акроним, который на русском звучит как “PIP установщик пакетов” или “Предпочитаемый установщик программ”. Это утилита командной строки, которая позволяет устанавливать, переустанавливать и деинсталлировать PyPI пакеты простой командой pip
.
Если вы когда-нибудь работали с командной строкой Windows и с терминалом на Linux или Mac и чувствуете себя уверенно, можете пропустить инструкции по установке.
Устанавливается ли PIP вместе с Python?
Если вы пользуетесь Python 2.7.9 (и выше) или Python 3.4 (и выше), PIP устанавливается вместе с Python по умолчанию. Если же у вас более старая версия Python, то сначала ознакомьтесь с инструкцией по установке.
Правильно ли Python установлен?
Вы должны быть уверены, что Python должным образом установлен на вашей системе. На Windows откройте командную строку с помощью комбинации Win+X
. На Mac запустите терминал с помощью Command+пробел
, а на Linux – комбинацией Ctrl+Alt+T
или как-то иначе именно для вашего дистрибутива.
Затем введите команду:
python --version
На Linux пользователям Python 3.x следует ввести:
python3 --version
Если вы получили номер версии (например, Python 2.7.5
), значит Python готов к использованию.
Если вы получили сообщение Python is not defined
(Python не установлен), значит, для начала вам следует установить Python. Это уже не по теме статьи. Подробные инструкции по установке Python читайте в теме: Скачать и установить Python.
Как установить PIP на Windows.
Следующие инструкции подойдут для Windows 7, Windows 8.1 и Windows 10.
- Скачайте установочный скрипт get-pip.py. Если у вас Python 3.2, версия get-pip.py должны быть такой же. В любом случае щелкайте правой кнопкой мыши на ссылке и нажмите “Сохранить как…” и сохраните скрипт в любую безопасную папку, например в “Загрузки”.
- Откройте командную строку и перейдите к каталогу с файлом get-pip.py.
- Запустите следующую команду:
python get-pip.py
Как установить PIP на Mac
Современные версии Mac идут с установленными Python и PIP. Так или иначе версия Python устаревает, а это не лучший вариант для серьёзного разработчика. Так что рекомендуется установить актуальные версии Python и PIP.
Если вы хотите использовать родную систему Python, но у вас нет доступного PIP, его можно установить следующей командой через терминал:
sudo easy_install pip
Если вы предпочитаете более свежие версии Python, используйте Homebrew. Следующие инструкции предполагают, что Homebrew уже установлен и готов к работе.
Установка Python с помощью Homebrew производится посредством одной команды:
brew install python
Будет установлена последняя версия Python, в которую может входить PIP. Если после успешной установки пакет недоступен, необходимо выполнить перелинковку Python следующей командой:
brew unlink python && brew link python
Как установить PIP на Linux
Если у вас дистрибутив Linux с уже установленным на нем Python, то скорее всего возможно установить PIP, используя системный пакетный менеджер. Это более удачный способ, потому что системные версии Python не слишком хорошо работают со скриптом get-pip.py, используемым в Windows и Mac.
Advanced Package Tool (Python 2.x)
sudo apt-get install python-pip
Advanced Package Tool (Python 3.x)
sudo apt-get install python3-pip
pacman Package Manager (Python 2.x)
sudo pacman -S python2-pip
pacman Package Manager (Python 3.x)
sudo pacman -S python-pip
Yum Package Manager (Python 2.x)
sudo yum upgrade python-setuptools
sudo yum install python-pip python-wheel
Yum Package Manager (Python 3.x)
sudo yum install python3 python3-wheel
Dandified Yum (Python 2.x)
sudo dnf upgrade python-setuptools
sudo dnf install python-pip python-wheel
Dandified Yum (Python 3.x)
sudo dnf install python3 python3-wheel
Zypper Package Manager (Python 2.x)
sudo zypper install python-pip python-setuptools python-wheel
Zypper Package Manager (Python 3.x)
sudo zypper install python3-pip python3-setuptools python3-wheel
Как установить PIP на Raspberry Pi
Как пользователь Raspberry, возможно, вы запускали Rapsbian до того, как появилась официальная и поддерживаемая версия системы. Можно установить другую систему, например, Ubuntu, но в этом случае вам придётся воспользоваться инструкциями по Linux.
Начиная с Rapsbian Jessie, PIP установлен по умолчанию. Это одна из серьёзных причин, чтобы обновиться до Rapsbian Jessie вместо использования Rapsbian Wheezy или Rapsbian Jessie Lite. Так или иначе, на старую версию, все равно можно установить PIP.
Для Python 2.x:
sudo apt-get install python-pip
Для Python 3.x:
sudo apt-get install python3-pip
На Rapsbian для Python 2.x следует пользоваться командой pip, а для Python 3.x — командой pip3 при использовании команд для PIP.
Как обновить PIP для Python
Пока PIP не слишком часто обновляется самостоятельно, очень важно постоянно иметь свежую версию. Это может иметь значение при исправлении багов, совместимости и дыр в защите.
К счастью, обновление PIP проходит просто и быстро.
Для Windows:
python -m pip install -U pip
Для Mac, Linux, или Raspberry Pi:
pip install -U pip
На текущих версиях Linux и Rapsbian Pi следует использовать команду pip3.
Как устанавливать библиотеки Python с помощью PIP
Если PIP работоспособен, можно начинать устанавливать пакеты из PyPI:
pip install package-name
Установка определённой версии вместо новейшей версии пакета:
pip install package-name==1.0.0
Поиск конкретного пакета:
pip search "query"
Просмотр деталей об установленном пакете:
pip show package-name
Список всех установленных пакетов:
pip list
Список всех устаревших пакетов:
pip list --outdated
Обновление устаревших пакетов:
pip install package-name --upgrade
Следует отметить, что старая версия пакета автоматически удаляется при обновлении до новой версии.
Полностью переустановить пакет:
pip install package-name --upgrade --force-reinstall
Полностью удалить пакет:
pip uninstall package-name
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.
In this tutorial, we will identify PIP for Python, when we use it, how to install it, how to check its version, how to configure it on Windows, and how to upgrade (or downgrade) it.
What Is PIP for Python?
PIP stands for «PIP Installs Packages», which is a recursive acronym (the one that refers to itself) coined by its creator. In more practical terms, PIP is a widely used package-management system designed to install libraries that aren’t included in the standard distribution of the Python programming language on our local machine — and then manage them from the command line.
By default, PIP fetches such libraries from Python Package Index (PyPI), which is a central online repository containing a vast collection of third-party packages for various applications. If necessary, PIP can also connect to another local or online repository as long as it complies to PEP 503.
How to Install PIP on Windows
Before proceeding to PIP installation on Windows, we need to make sure that Python is already installed and PIP is not installed.
Check If Python Is Available
To verify that Python is available on our local machine, we need to open the command line (in Windows search, type cmd
and press Enter
to open Command Prompt or right-click on the Start
button and select Windows PowerShell
), type python
, and press Enter
.
If Python is properly installed, we will see a notification like the one below:
Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32 Type "help," "copyright," "credits," or "license" for more information.
In the opposite case, we will see the following notification:
'python' is not recognized as an internal or external command, operable program or batch file.
This means that Python is either not installed on our local machine or is installed incorrectly and needs setting system variables. If you need further guidance on how to properly install Python on Windows, you can use this article in the Dataquest blog: Tutorial: Installing Python on Windows.
Check If PIP Is Already Installed
Now that we verified that Python is installed on Windows (or, if it was not, have installed it), let’s check if PIP is already installed on our system.
The latest releases Python 3.4+ and Python 2.7.9+, as well as the virtual environments virtualenv
and pyvenv
, automatically ship with PIP (we can check our Python version by running python --version
or python -V
in the command line). However, the older versions of Python don’t have this advantage by default. If we use an older Python release and cannot upgrade it for some reason (e.g., when we have to work with the projects made in old versions of Python incompatible with the newer versions), we may need to manually download and install PIP on Windows.
To check if PIP is already installed on Windows, we should open the command line again, type pip
, and press Enter
.
If PIP is installed, we will receive a long notification explaining the program usage, all the available commands and options. Otherwise, if PIP is not installed, the output will be:
'pip' is not recognized as an internal or external command, operable program or batch file.
This is exactly the case when we have to manually install PIP on Windows.
Download PIP
Before installing PIP, we have to download the get-pip.py
file. We can do this two ways:
- Go to https://bootstrap.pypa.io/get-pip.py and save this file as
get-pip.py
in the same folder where Python is located.
By default, the Python installation is stored in the folderAppData
. The entire path could look like the following:
C:\Users\User\AppData\Local\Programs\Python\Python310
The folder User
can be called differently on a particular machine, and also the final folder in the above path depends on the version of Python. In our case – Python 3.10:
- Open the command line and navigate to the folder where Python is stored using the
cd
command (see the previous point if you are not sure about Python’s location).
Now, run the following curl command:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
Install PIP on Windows
Now that we downloaded the get-pip.py
file, we need to complete the followings steps.
- Open the command line
- Navigate to the folder where Python and the
get-pip.py
file are stored using thecd
command - Launch the installer by running the following command:
python get-pip.py
After a quick installation process, a message appears with all the details of the installation, and the final line appears as follows:
Successfully installed pip-22.0.1 wheel-0.37.1
PIP is now successfully installed on Windows.
Verify the PIP Installation Process and Check the PIP Version
To double-check if PIP has been installed properly and check its version, we need to run one of these commands in the command line:
pip --version
or
pip -V
If PIP is installed correctly, we will see a message indicating the version of PIP and its location on the local system, like the following:
pip 22.0.2 from C:\Users\Utente\AppData\Local\Programs\Python\Python310\lib\site-packages\pip (python 3.10)
.
If instead, an error is thrown, it is necessary to repeat the installation process.
Add PIP to Windows Environment Variables
To be able to run PIP without issues from any folder in the command line (rather than navigating every time to the folder where the PIP installer is stored, as we did earlier), we have to add the path to the folder with the get-pip.py
file to Windows environment variables. This is especially important in that rare case when, we have installed several versions of Python, including old ones. In this situation, to avoid installing PIP separately for each old version of Python, we should install it only for one of them and then perform the following steps:
- Open
Control Panel
(typing it in Windows search), selectSystem and Security
, then selectSystem
. - Go to the end of the opened window and select
Advanced system settings
:
- Click
Environment Variables
:
- In the
System variables
section, find and double-click the variablePath
:
- Click
New
and add the path to the folder where the PIP installer is stored:
- Click
OK
to confirm modifications.
Upgrade PIP on Windows
Sometimes, we may need to update PIP on Windows to the latest version to keep it up-to-date and working flawlessly. For this purpose, we can run the following command in the command line:
python -m pip install --upgrade pip
As a result, the old version of PIP will be uninstalled and the most recent release will be installed.
Downgrade PIP on Windows
We can also want to downgrade PIP to a specific older version. This operation may be necessary in certain cases, for example, if a new version works with some compatibility issues. To downgrade PIP on Windows, we need to open the command line and run a command with the following syntax:
python -m pip install pip==<version>
Let’s say, we want to downgrade it to v20.3. Then the exact command will be:
python -m pip install pip==20.3
After downgrading PIP, we can verify that we now have the necessary version of it by running python -V
.
Conclusion
In this tutorial we covered various topics regarding the installation of PIP on Windows:
- How PIP works
- How to check if Python and PIP are already installed
- When it may be necessary to manually install PIP on Windows
- How to download and install PIP on Windows
- How to verify if PIP has been successfully installed and check its version
- How to configure PIP on Windows and when it may be necessary
- When and how to upgrade or downgrade PIP on Windows
Now that we have PIP properly installed on Windows, we can begin using it to manage Python libraries. Let’s start with running pip help
in the command line and exploring the available commands and options for this program.