Edit 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
$ python -m pip.pyz --help
MacOS
$ python -m pip.pyz --help
Windows
then the currently active Python interpreter will be used.
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.7, 3.8, 3.9, 3.10, 3.11, 3.12, 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.
Project description
pip is the package installer for Python. You can use pip to install packages from the Python Package Index and other indexes.
Please take a look at our documentation for how to install and use pip:
-
Installation
-
Usage
We release updates regularly, with a new version every 3 months. Find more details in our documentation:
-
Release notes
-
Release process
In pip 20.3, we’ve made a big improvement to the heart of pip; learn more. We want your input, so sign up for our user experience research studies to help us do it right.
Note: pip 21.0, in January 2021, removed Python 2 support, per pip’s Python 2 support policy. Please migrate to Python 3.
If you find bugs, need help, or want to talk to the developers, please use our mailing lists or chat rooms:
-
Issue tracking
-
Discourse channel
-
User IRC
If you want to get involved head over to GitHub to get the source code, look at our development documentation and feel free to jump on the developer mailing lists and chat rooms:
-
GitHub page
-
Development documentation
-
Development IRC
Code of Conduct
Everyone interacting in the pip project’s codebases, issue trackers, chat
rooms, and mailing lists is expected to follow the PSF Code of Conduct.
Download files
Download the file for your platform. If you’re not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
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.
Note
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.
Unix/macOS
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:
python3 -m pip install --user --upgrade pip python3 -m pip --version
Afterwards, you should have the latest version of pip installed in your
user site:
pip 21.1.3 from $HOME/.local/lib/python3.9/site-packages (python 3.9)
Windows
The Python installers for Windows include pip. You can make sure that pip is
up-to-date by running:
py -m pip install --upgrade pip py -m pip --version
Afterwards, you should have the latest version of pip:
pip 21.1.3 from c:\python39\lib\site-packages (Python 3.9.4)
Installing virtualenv¶
Note
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.
Unix/macOS
python3 -m pip install --user virtualenv
Windows
py -m pip install --user virtualenv
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.
Note
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:
It should be in the env
directory:
Unix/macOS
Windows
...\env\Scripts\python.exe
As long as your virtual environment is activated pip will install packages into that
specific environment and you’ll be able to import and use packages in your
Python application.
Leaving the virtual environment¶
If you want to switch projects or otherwise leave your virtual environment, simply run:
If you want to re-enter the virtual environment just follow the same instructions above
about activating a virtual environment. There’s no need to re-create the virtual environment.
Installing packages¶
Now that you’re in your virtual environment you can install packages. Let’s install the
Requests library from the Python Package Index (PyPI):
Unix/macOS
python3 -m pip install requests
Windows
py -m pip install requests
pip should download requests and all of its dependencies and install them:
Collecting requests Using cached requests-2.18.4-py2.py3-none-any.whl Collecting chardet<3.1.0,>=3.0.2 (from requests) Using cached chardet-3.0.4-py2.py3-none-any.whl Collecting urllib3<1.23,>=1.21.1 (from requests) Using cached urllib3-1.22-py2.py3-none-any.whl Collecting certifi>=2017.4.17 (from requests) Using cached certifi-2017.7.27.1-py2.py3-none-any.whl Collecting idna<2.7,>=2.5 (from requests) Using cached idna-2.6-py2.py3-none-any.whl Installing collected packages: chardet, urllib3, certifi, idna, requests Successfully installed certifi-2017.7.27.1 chardet-3.0.4 idna-2.6 requests-2.18.4 urllib3-1.22
Installing specific versions¶
pip allows you to specify which version of a package to install using
version specifiers. For example, to install
a specific version of requests
:
Unix/macOS
python3 -m pip install 'requests==2.18.4'
Windows
py -m pip install "requests==2.18.4"
To install the latest 2.x
release of requests:
Unix/macOS
python3 -m pip install 'requests>=2.0.0,<3.0.0'
Windows
py -m pip install "requests>=2.0.0,<3.0.0"
To install pre-release versions of packages, use the --pre
flag:
Unix/macOS
python3 -m pip install --pre requests
Windows
py -m pip install --pre requests
Installing from source¶
pip can install a package directly from source, for example:
Unix/macOS
cd google-auth python3 -m pip install .
Windows
cd google-auth
py -m pip install .
Additionally, pip can install packages from source in
development mode,
meaning that changes to the source directory will immediately affect the
installed package without needing to re-install:
Unix/macOS
python3 -m pip install --editable .
Windows
py -m pip install --editable .
Installing from version control systems¶
pip can install packages directly from their version control system. For
example, you can install directly from a git repository:
google-auth @ git+https://github.com/GoogleCloudPlatform/google-auth-library-python.git
For more information on supported version control systems and syntax, see pip’s
documentation on VCS Support.
Installing from local archives¶
If you have a local copy of a Distribution Package’s archive (a zip,
wheel, or tar file) you can install it directly with pip:
Unix/macOS
python3 -m pip install requests-2.18.4.tar.gz
Windows
py -m pip install requests-2.18.4.tar.gz
If you have a directory containing archives of multiple packages, you can tell
pip to look for packages there and not to use the
Python Package Index (PyPI) at all:
Unix/macOS
python3 -m pip install --no-index --find-links=/local/dir/ requests
Windows
py -m pip install --no-index --find-links=/local/dir/ requests
This is useful if you are installing packages on a system with limited
connectivity or if you want to strictly control the origin of distribution
packages.
Using other package indexes¶
If you want to download packages from a different index than the
Python Package Index (PyPI), you can use the --index-url
flag:
Unix/macOS
python3 -m pip install --index-url http://index.example.com/simple/ SomeProject
Windows
py -m pip install --index-url http://index.example.com/simple/ SomeProject
If you want to allow packages from both the Python Package Index (PyPI)
and a separate index, you can use the --extra-index-url
flag instead:
Unix/macOS
python3 -m pip install --extra-index-url http://index.example.com/simple/ SomeProject
Windows
py -m pip install --extra-index-url http://index.example.com/simple/ SomeProject
Upgrading packages¶
pip can upgrade packages in-place using the --upgrade
flag. For example, to
install the latest version of requests
and all of its dependencies:
Unix/macOS
python3 -m pip install --upgrade requests
Windows
py -m pip install --upgrade requests
Using requirements files¶
Instead of installing packages individually, pip allows you to declare all
dependencies in a Requirements File. For
example you could create a requirements.txt
file containing:
requests==2.18.4 google-auth==1.1.0
And tell pip to install all of the packages in this file using the -r
flag:
Unix/macOS
python3 -m pip install -r requirements.txt
Windows
py -m pip install -r requirements.txt
Freezing dependencies¶
Pip can export a list of all installed packages and their versions using the
freeze
command:
Which will output a list of package specifiers such as:
cachetools==2.0.1 certifi==2017.7.27.1 chardet==3.0.4 google-auth==1.1.1 idna==2.6 pyasn1==0.3.6 pyasn1-modules==0.1.4 requests==2.18.4 rsa==3.4.2 six==1.11.0 urllib3==1.22
This is useful for creating Requirements Files that can re-create
the exact versions of all packages installed in an environment.
Как любой серьёзный язык программирования, 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
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.