Зачастую возникает необходимость обновления PIP. В данном руководстве будет дана поэтапная инструкция для обновления PIP в Windows.
Содержание статьи
- План обновления PIP в Windows
- Проверка текущей версии PIP
- Инструмент для обновления PIP в Windows
- Как вернуться к предыдущей версии PIP
Столкнуться с необходимостью обновления PIP можно при установке любого пакета, используя PIP.
Выводится следующее сообщение:
Вы используете версию pip 19.3.1; однако, доступна версия 20.1.1. Вам стоит сделать обновление через команду ‘python -m pip install –upgrade pip’.
Есть вопросы по Python?
На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!
Telegram Чат & Канал
Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!
Паблик VK
Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!
Для обновления PIP в Windows нужно открыть Windows Command Prompt, а затем набрать/скопировать туда указанную команду. Обратите внимание, что данный метод сработает только если у вас уже добавлен Python в Windows PATH. Ничего страшного, если вы не знаете, что это такое. Далее мы подробно разберем все шаги обновления PIP.
python —m pip install —upgrade pip |
В поисковике Windows наберите Command Prompt (Командная строка):
Затем откройте Command Prompt (Командную строку). Во избежание проблем с уровнем доступа сделайте это от имени администратора. Для этого кликлинте правой кнопкой мыши и выберите пункт Run as administrator (Запустить от имени администратора):
В командной строке наберите cd
, чтобы удостовериться, что в начальной точке только название диска:
Нажмите Enter. Вы увидите название диска C:>
Найдите путь к Python, что является папкой, куда установлен Python.
В нашем случае путь приложения Python следующий:
C:UsersRonAppDataLocalProgramsPythonPython37-32
После получения пути к Python наберите следующую команду в командной строке: cd
, за которым следует путь к приложению Python.
В нашем случае это выглядит следующим образом:
Нажмите Enter, вы увидите:
Обновите PIP, использовав данную команду, затем нажмите Enter:
python —m pip install —upgrade pip |
В командной строке команда будет выглядеть следующим образом:
Обратите внимание, что будет установлена последняя версия PIP:
Проверка текущей версии PIP
Для проверки текущей версии PIP нужно использовать путь скриптов Python вместо пути приложения.
Наберите cd
, чтобы убедиться, что стартовой точкой является только название диска:
Затем найдите путь к Python скриптов. Папка скриптов должна находиться внутри пути приложения Pythоn.
В нашем случае путь Python скриптов следующий:
C:UsersRonAppDataLocalProgramsPythonPython37-32Scripts
Затем наберите cd
, после которой следует путь к Python скриптам, и нажмите Enter.
В конечном итоге наберите следующую команду для проверки версии PIP:
Нажмите Enter, после этого будет показана версия PIP.
Разберем простой инструмент для обновления PIP.
Обратите внимание, что вам нужно добавить Python к Windows PATH для использования данного инструмента.
Далее дан полный код Python для инструмента обновления PIP используя Tkinter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import os import tkinter as tk root= tk.Tk() canvas1 = tk.Canvas(root, width = 300, height = 350, bg = ‘lightsteelblue2’, relief = ‘raised’) canvas1.pack() label1 = tk.Label(root, text=‘Upgrade PIP’, bg = ‘lightsteelblue2’) label1.config(font=(‘helvetica’, 20)) canvas1.create_window(150, 80, window=label1) def upgradePIP (): os.system(‘start cmd /k python.exe -m pip install —upgrade pip’) button1 = tk.Button(text=‘ Upgrade PIP ‘, command=upgradePIP, bg=‘green’, fg=‘white’, font=(‘helvetica’, 12, ‘bold’)) canvas1.create_window(150, 180, window=button1) root.mainloop() |
Просто запустите код и затем нажмите на кнопку Upgrade PIP, после чего команда выполнится.
Что, если нужно откатиться к предыдущей версии PIP?
Выполнив следующие шаги, вернуться к предыдущей версии PIP не составит особого труда.
Как вернуться к предыдущей версии PIP
Перейдите в папку где установлен Python. Если сейчас настроен путь к скриптам, тогда просто наберите cd ..
(и затем нажмите Enter), и вы вернетесь к папке с установленным Python.
Предположим, нам нужно вернуться к версии 18.1.
Для этого просто наберите следующую команду и затем нажмите Enter:
python —m pip install pip==18.1 |
Вы должны увидеть указанную версию PIP:
Являюсь администратором нескольких порталов по обучению языков программирования Python, Golang и Kotlin. В составе небольшой команды единомышленников, мы занимаемся популяризацией языков программирования на русскоязычную аудиторию. Большая часть статей была адаптирована нами на русский язык и распространяется бесплатно.
E-mail: vasile.buldumac@ati.utm.md
Образование
Universitatea Tehnică a Moldovei (utm.md)
- 2014 — 2018 Технический Университет Молдовы, ИТ-Инженер. Тема дипломной работы «Автоматизация покупки и продажи криптовалюты используя технический анализ»
- 2018 — 2020 Технический Университет Молдовы, Магистр, Магистерская диссертация «Идентификация человека в киберпространстве по фотографии лица»
I want to use python3.5 for development, but many times when I install the module for python 3.5, it always fails. The terminal tells me that a higher version is available, but it doesn’t work when I upgrade it.
Josh Correia
3,3763 gold badges29 silver badges46 bronze badges
asked Jul 27, 2016 at 12:42
5
You are using pip3 to install flask-script which is associated with python 3.5. However, you are trying to upgrade pip associated with the python 2.7, try running pip3 install --upgrade pip
.
It might be a good idea to take some time and read about virtual environments in Python. It isn’t a best practice to install all of your packages to the base python installation. This would be a good start: http://docs.python-guide.org/en/latest/dev/virtualenvs/
answered Jul 27, 2016 at 12:50
JanHakJanHak
1,5951 gold badge8 silver badges9 bronze badges
2
To upgrade your pip3, try running:
sudo -H pip3 install --upgrade pip
Your pip may move from /bin
to /usr/local/bin
To upgrade pip as well, you can follow it by:
sudo -H pip2 install --upgrade pip
answered Jul 5, 2017 at 10:29
BhushanDhamaleBhushanDhamale
1,2051 gold badge9 silver badges12 bronze badges
6
Try this command:
pip3 install --upgrade setuptools pip
answered Mar 7, 2018 at 15:28
El Fadel AnasEl Fadel Anas
1,4912 gold badges18 silver badges25 bronze badges
5
First decide which pip you want to upgrade, i.e. just pip or pip3.
Mostly it’ll be pip3 because pip is used by the system, so I won’t recommend upgrading pip.
The difference between pip and pip3 is that
NOTE: I’m referring to PIP that is at the BEGINNING of the command
line.
pip is used by python version 2, i.e. python2
and
pip3 is used by python version 3, i.e. python3
For upgrading pip3: # This will upgrade python3 pip.
pip3 install --upgrade pip
For upgrading pip: # This will upgrade python2 pip.
pip install --upgrade pip
This will upgrade your existing pip to the latest version.
answered Jan 12, 2020 at 7:40
2
The Problem
You use pip
(the Python 2 one). Now you want to upgrade pip
(the Python 3 one). After that, pip
is the Python 3 one.
The solution
Use pip2
and pip3
. This way it is explicit.
If you want to use pip
, just check where it is (which pip
) and change the link. For example:
$ which pip
/usr/local/bin/pip
$ pip --version
pip 9.0.1 from /usr/local/lib/python3.5/dist-packages (python 3.5)
$ which pip2
/usr/local/bin/pip2
$ sudo rm /usr/local/bin/pip
$ sudo ln -s /usr/local/bin/pip2 /usr/local/bin/pip
$ pip --version
pip 9.0.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)
answered Sep 26, 2017 at 10:58
Martin ThomaMartin Thoma
118k153 gold badges590 silver badges913 bronze badges
-
for Python 3:
python3 -m pip install --upgrade pip
-
for Python 2:
python2 -m pip install --upgrade pip
answered May 18, 2021 at 11:35
Ali MUSAAli MUSA
1791 silver badge2 bronze badges
What worked for me was the following command:
python -m pip install --upgrade pip
answered Oct 26, 2018 at 16:39
pip3 install --upgrade pip
worked for me
answered Jul 6, 2019 at 20:18
0
In Ubuntu 18.04, below are the steps that I followed.
python3 -m pip install --upgrade pip
For some reason you will be getting an error, and that be fixed by making bash forget the wrongly referenced locations using the following command.
hash -r pip
answered Nov 19, 2019 at 16:12
SuperNovaSuperNova
24k6 gold badges90 silver badges62 bronze badges
If you have 2 versions of Python (eg: 2.7.x and 3.6), you need do:
- add the path of 2.x to system PATH
- add the path of 3.x to system PATH
pip3 install --upgrade pip setuptools wheel
for example, in my .zshrc file:
export PATH=/usr/local/Cellar/python@2/2.7.15/bin:/usr/local/Cellar/python/3.6.5/bin:$PATH
You can exec command pip --version
and pip3 --version
check the pip from the special version. Because if don’t add Python path to $PATH, and exec pip3 install --upgrade pip setuptools wheel
, your pip will be changed to pip from python3, but the pip should from python2.x
Stephen Rauch♦
46.7k31 gold badges109 silver badges131 bronze badges
answered Jun 14, 2018 at 1:16
This worked for me (mac)
sudo curl https://bootstrap.pypa.io/get-pip.py | python
answered Aug 19, 2020 at 18:06
Aman KumarAman Kumar
2324 silver badges11 bronze badges
If you try to run
sudo -H pip3 install --upgrade pip3
you will get the following error:
WARNING: You are using pip version 19.2.3, however version 21.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
but if you upgrade using the suggested command:
pip install --upgrade pip
then, the legacy pip will be upgraded, so what I did is the following:
which pip3
and I located my pip3 installation (just in case the following command wouldn’t upgrade the legacy pip. Then i changed to that directory and upgraded pip3 using the following commands: (your directory could be different)
cd /Library/Frameworks/Python.framework/Versions/3.8/bin
sudo -H pip3 install --upgrade pip
after this:
pip --version
will still show the legacy version, while
pip3 --version
will show pip 21.0.1
answered Feb 1, 2021 at 23:45
Dany BalianDany Balian
6087 silver badges16 bronze badges
User Guide
Running pip
pip is a command line program. When you install pip, a pip
command is added
to your system, which can be run from the command prompt as follows:
.. tab:: Unix/macOS .. code-block:: shell python -m pip <pip arguments> ``python -m pip`` executes pip using the Python interpreter you specified as python. So ``/usr/bin/python3.7 -m pip`` means you are executing pip for your interpreter located at ``/usr/bin/python3.7``.
.. tab:: Windows .. code-block:: shell py -m pip <pip arguments> ``py -m pip`` executes pip using the latest Python interpreter you have installed. For more details, read the `Python Windows launcher`_ docs.
Installing Packages
pip supports installing from PyPI, version control, local projects, and
directly from distribution files.
The most common scenario is to install from PyPI using :ref:`Requirement
Specifiers`
.. tab:: Unix/macOS .. code-block:: shell 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
.. tab:: Windows .. code-block:: shell 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
For more information and examples, see the :ref:`pip install` reference.
Basic Authentication Credentials
This is now covered in :doc:`topics/authentication`.
netrc Support
This is now covered in :doc:`topics/authentication`.
Keyring Support
This is now covered in :doc:`topics/authentication`.
Using a Proxy Server
When installing packages from PyPI, pip requires internet access, which
in many corporate environments requires an outbound HTTP proxy server.
pip can be configured to connect through a proxy server in various ways:
- using the
--proxy
command-line option to specify a proxy in the form
scheme://[user:passwd@]proxy.server:port
- using
proxy
in a :ref:`config-file` - by setting the standard environment-variables
http_proxy
,https_proxy
andno_proxy
. - using the environment variable
PIP_USER_AGENT_USER_DATA
to include
a JSON-encoded string in the user-agent variable used in pip’s requests.
Requirements Files
«Requirements files» are files containing a list of items to be
installed using :ref:`pip install` like so:
.. tab:: Unix/macOS .. code-block:: shell python -m pip install -r requirements.txt
.. tab:: Windows .. code-block:: shell py -m pip install -r requirements.txt
Details on the format of the files are here: :ref:`requirements-file-format`.
Logically, a Requirements file is just a list of :ref:`pip install` arguments
placed in a file. Note that you should not rely on the items in the file being
installed by pip in any particular order.
In practice, there are 4 common uses of Requirements files:
-
Requirements files are used to hold the result from :ref:`pip freeze` for the
purpose of achieving :doc:`topics/repeatable-installs`. In
this case, your requirement file contains a pinned version of everything that
was installed whenpip freeze
was run... tab:: Unix/macOS .. code-block:: shell python -m pip freeze > requirements.txt python -m pip install -r requirements.txt
.. tab:: Windows .. code-block:: shell py -m pip freeze > requirements.txt py -m pip install -r requirements.txt
-
Requirements files are used to force pip to properly resolve dependencies.
pip 20.2 and earlier doesn’t have true dependency resolution, but instead simply uses the first
specification it finds for a project. E.g. ifpkg1
requires
pkg3>=1.0
andpkg2
requirespkg3>=1.0,<=2.0
, and ifpkg1
is
resolved first, pip will only usepkg3>=1.0
, and could easily end up
installing a version ofpkg3
that conflicts with the needs ofpkg2
.
To solve this problem, you can placepkg3>=1.0,<=2.0
(i.e. the correct
specification) into your requirements file directly along with the other top
level requirements. Like so:pkg1 pkg2 pkg3>=1.0,<=2.0
-
Requirements files are used to force pip to install an alternate version of a
sub-dependency. For example, supposeProjectA
in your requirements file
requiresProjectB
, but the latest version (v1.3) has a bug, you can force
pip to accept earlier versions like so:ProjectA ProjectB<1.3
-
Requirements files are used to override a dependency with a local patch that
lives in version control. For example, suppose a dependency
SomeDependency
from PyPI has a bug, and you can’t wait for an upstream
fix.
You could clone/copy the src, make the fix, and place it in VCS with the tag
sometag
. You’d reference it in your requirements file with a line like
so:git+https://myvcs.com/some_dependency@sometag#egg=SomeDependency
If
SomeDependency
was previously a top-level requirement in your
requirements file, then replace that line with the new line. If
SomeDependency
is a sub-dependency, then add the new line.
It’s important to be clear that pip determines package dependencies using
install_requires metadata,
not by discovering requirements.txt
files embedded in projects.
See also:
- :ref:`requirements-file-format`
- :ref:`pip freeze`
- «setup.py vs requirements.txt» (an article by Donald Stufft)
Constraints Files
Constraints files are requirements files that only control which version of a
requirement is installed, not whether it is installed or not. Their syntax and
contents is a subset of :ref:`Requirements Files`, with several kinds of syntax
not allowed: constraints must have a name, they cannot be editable, and they
cannot specify extras. In terms of semantics, there is one key difference:
Including a package in a constraints file does not trigger installation of the
package.
Use a constraints file like so:
.. tab:: Unix/macOS .. code-block:: shell python -m pip install -c constraints.txt
.. tab:: Windows .. code-block:: shell py -m pip install -c constraints.txt
Constraints files are used for exactly the same reason as requirements files
when you don’t know exactly what things you want to install. For instance, say
that the «helloworld» package doesn’t work in your environment, so you have a
local patched version. Some things you install depend on «helloworld», and some
don’t.
One way to ensure that the patched version is used consistently is to
manually audit the dependencies of everything you install, and if «helloworld»
is present, write a requirements file to use when installing that thing.
Constraints files offer a better way: write a single constraints file for your
organisation and use that everywhere. If the thing being installed requires
«helloworld» to be installed, your fixed version specified in your constraints
file will be used.
Constraints file support was added in pip 7.1. In :ref:`Resolver
changes 2020` we did a fairly comprehensive overhaul, removing several
undocumented and unsupported quirks from the previous implementation,
and stripped constraints files down to being purely a way to specify
global (version) limits for packages.
Installing from Wheels
«Wheel» is a built, archive format that can greatly speed installation compared
to building and installing from source archives. For more information, see the
Wheel docs , PEP 427, and PEP 425.
pip prefers Wheels where they are available. To disable this, use the
:ref:`—no-binary <install_—no-binary>` flag for :ref:`pip install`.
If no satisfactory wheels are found, pip will default to finding source
archives.
To install directly from a wheel archive:
.. tab:: Unix/macOS .. code-block:: shell python -m pip install SomePackage-1.0-py2.py3-none-any.whl
.. tab:: Windows .. code-block:: shell py -m pip install SomePackage-1.0-py2.py3-none-any.whl
To include optional dependencies provided in the provides_extras
metadata in the wheel, you must add quotes around the install target
name:
.. tab:: Unix/macOS .. code-block:: shell python -m pip install './somepackage-1.0-py2.py3-none-any.whl[my-extras]'
.. tab:: Windows .. code-block:: shell py -m pip install './somepackage-1.0-py2.py3-none-any.whl[my-extras]'
Note
In the future, the path[extras]
syntax may become deprecated. It is
recommended to use PEP 508 syntax wherever possible.
For the cases where wheels are not available, pip offers :ref:`pip wheel` as a
convenience, to build wheels for all your requirements and dependencies.
:ref:`pip wheel` requires the wheel package to be installed, which provides the
«bdist_wheel» setuptools extension that it uses.
To build wheels for your requirements and all their dependencies to a local
directory:
.. tab:: Unix/macOS .. code-block:: shell python -m pip install wheel python -m pip wheel --wheel-dir=/local/wheels -r requirements.txt
.. tab:: Windows .. code-block:: shell py -m pip install wheel py -m pip wheel --wheel-dir=/local/wheels -r requirements.txt
And then to install those requirements just using your local directory of
wheels (and not from PyPI):
.. tab:: Unix/macOS .. code-block:: shell python -m pip install --no-index --find-links=/local/wheels -r requirements.txt
.. tab:: Windows .. code-block:: shell py -m pip install --no-index --find-links=/local/wheels -r requirements.txt
Uninstalling Packages
pip is able to uninstall most packages like so:
.. tab:: Unix/macOS .. code-block:: shell python -m pip uninstall SomePackage
.. tab:: Windows .. code-block:: shell py -m pip uninstall SomePackage
pip also performs an automatic uninstall of an old version of a package
before upgrading to a newer version.
For more information and examples, see the :ref:`pip uninstall` reference.
Listing Packages
To list installed packages:
.. tab:: Unix/macOS .. code-block:: console $ python -m pip list docutils (0.9.1) Jinja2 (2.6) Pygments (1.5) Sphinx (1.1.2)
.. tab:: Windows .. code-block:: console C:> py -m pip list docutils (0.9.1) Jinja2 (2.6) Pygments (1.5) Sphinx (1.1.2)
To list outdated packages, and show the latest version available:
.. tab:: Unix/macOS .. code-block:: console $ python -m pip list --outdated docutils (Current: 0.9.1 Latest: 0.10) Sphinx (Current: 1.1.2 Latest: 1.1.3)
.. tab:: Windows .. code-block:: console C:> py -m pip list --outdated docutils (Current: 0.9.1 Latest: 0.10) Sphinx (Current: 1.1.2 Latest: 1.1.3)
To show details about an installed package:
.. tab:: Unix/macOS .. code-block:: console $ python -m pip show sphinx --- Name: Sphinx Version: 1.1.3 Location: /my/env/lib/pythonx.x/site-packages Requires: Pygments, Jinja2, docutils
.. tab:: Windows .. code-block:: console C:> py -m pip show sphinx --- Name: Sphinx Version: 1.1.3 Location: /my/env/lib/pythonx.x/site-packages Requires: Pygments, Jinja2, docutils
For more information and examples, see the :ref:`pip list` and :ref:`pip show`
reference pages.
Searching for Packages
pip can search PyPI for packages using the pip search
command:
.. tab:: Unix/macOS .. code-block:: shell python -m pip search "query"
.. tab:: Windows .. code-block:: shell py -m pip search "query"
The query will be used to search the names and summaries of all
packages.
For more information and examples, see the :ref:`pip search` reference.
Configuration
This is now covered in :doc:`topics/configuration`.
Config file
This is now covered in :doc:`topics/configuration`.
Environment Variables
This is now covered in :doc:`topics/configuration`.
Config Precedence
This is now covered in :doc:`topics/configuration`.
Command Completion
pip comes with support for command line completion in bash, zsh and fish.
To setup for bash:
python -m pip completion --bash >> ~/.profile
To setup for zsh:
python -m pip completion --zsh >> ~/.zprofile
To setup for fish:
python -m pip completion --fish > ~/.config/fish/completions/pip.fish
To setup for powershell:
python -m pip completion --powershell | Out-File -Encoding default -Append $PROFILE
Alternatively, you can use the result of the completion
command directly
with the eval function of your shell, e.g. by adding the following to your
startup file:
eval "`pip completion --bash`"
Installing from local packages
In some cases, you may want to install from local packages only, with no traffic
to PyPI.
First, download the archives that fulfill your requirements:
.. tab:: Unix/macOS .. code-block:: shell python -m pip download --destination-directory DIR -r requirements.txt
.. tab:: Windows .. code-block:: shell py -m pip download --destination-directory DIR -r requirements.txt
Note that pip download
will look in your wheel cache first, before
trying to download from PyPI. If you’ve never installed your requirements
before, you won’t have a wheel cache for those items. In that case, if some of
your requirements don’t come as wheels from PyPI, and you want wheels, then run
this instead:
.. tab:: Unix/macOS .. code-block:: shell python -m pip wheel --wheel-dir DIR -r requirements.txt
.. tab:: Windows .. code-block:: shell py -m pip wheel --wheel-dir DIR -r requirements.txt
Then, to install from local only, you’ll be using :ref:`—find-links
<install_—find-links>` and :ref:`—no-index <install_—no-index>` like so:
.. tab:: Unix/macOS .. code-block:: shell python -m pip install --no-index --find-links=DIR -r requirements.txt
.. tab:: Windows .. code-block:: shell py -m pip install --no-index --find-links=DIR -r requirements.txt
«Only if needed» Recursive Upgrade
pip install --upgrade
now has a --upgrade-strategy
option which
controls how pip handles upgrading of dependencies. There are 2 upgrade
strategies supported:
eager
: upgrades all dependencies regardless of whether they still satisfy
the new parent requirementsonly-if-needed
: upgrades a dependency only if it does not satisfy the new
parent requirements
The default strategy is only-if-needed
. This was changed in pip 10.0 due to
the breaking nature of eager
when upgrading conflicting dependencies.
It is important to note that --upgrade
affects direct requirements (e.g.
those specified on the command-line or via a requirements file) while
--upgrade-strategy
affects indirect requirements (dependencies of direct
requirements).
As an example, say SomePackage
has a dependency, SomeDependency
, and
both of them are already installed but are not the latest available versions:
pip install SomePackage
: will not upgrade the existingSomePackage
or
SomeDependency
.pip install --upgrade SomePackage
: will upgradeSomePackage
, but not
SomeDependency
(unless a minimum requirement is not met).pip install --upgrade SomePackage --upgrade-strategy=eager
: upgrades both
SomePackage
andSomeDependency
.
As an historic note, an earlier «fix» for getting the only-if-needed
behaviour was:
.. tab:: Unix/macOS .. code-block:: shell python -m pip install --upgrade --no-deps SomePackage python -m pip install SomePackage
.. tab:: Windows .. code-block:: shell py -m pip install --upgrade --no-deps SomePackage py -m pip install SomePackage
A proposal for an upgrade-all
command is being considered as a safer
alternative to the behaviour of eager upgrading.
User Installs
With Python 2.6 came the «user scheme» for installation,
which means that all Python distributions support an alternative install
location that is specific to a user. The default location for each OS is
explained in the python documentation for the site.USER_BASE variable.
This mode of installation can be turned on by specifying the :ref:`—user
<install_—user>` option to pip install
.
Moreover, the «user scheme» can be customized by setting the
PYTHONUSERBASE
environment variable, which updates the value of
site.USER_BASE
.
To install «SomePackage» into an environment with site.USER_BASE
customized to
‘/myappenv’, do the following:
.. tab:: Unix/macOS .. code-block:: shell export PYTHONUSERBASE=/myappenv python -m pip install --user SomePackage
.. tab:: Windows .. code-block:: shell set PYTHONUSERBASE=c:/myappenv py -m pip install --user SomePackage
pip install --user
follows four rules:
- When globally installed packages are on the python path, and they conflict
with the installation requirements, they are ignored, and not
uninstalled. - When globally installed packages are on the python path, and they satisfy
the installation requirements, pip does nothing, and reports that
requirement is satisfied (similar to how global packages can satisfy
requirements when installing packages in a--system-site-packages
virtualenv). - pip will not perform a
--user
install in a--no-site-packages
virtualenv (i.e. the default kind of virtualenv), due to the user site not
being on the python path. The installation would be pointless. - In a
--system-site-packages
virtualenv, pip will not install a package
that conflicts with a package in the virtualenv site-packages. The —user
installation would lack sys.path precedence and be pointless.
To make the rules clearer, here are some examples:
From within a --no-site-packages
virtualenv (i.e. the default kind):
.. tab:: Unix/macOS .. code-block:: console $ python -m pip install --user SomePackage Can not perform a '--user' install. User site-packages are not visible in this virtualenv.
.. tab:: Windows .. code-block:: console C:> py -m pip install --user SomePackage Can not perform a '--user' install. User site-packages are not visible in this virtualenv.
From within a --system-site-packages
virtualenv where SomePackage==0.3
is already installed in the virtualenv:
.. tab:: Unix/macOS .. code-block:: console $ python -m pip install --user SomePackage==0.4 Will not install to the user site because it will lack sys.path precedence
.. tab:: Windows .. code-block:: console C:> py -m pip install --user SomePackage==0.4 Will not install to the user site because it will lack sys.path precedence
From within a real python, where SomePackage
is not installed globally:
.. tab:: Unix/macOS .. code-block:: console $ python -m pip install --user SomePackage [...] Successfully installed SomePackage
.. tab:: Windows .. code-block:: console C:> py -m pip install --user SomePackage [...] Successfully installed SomePackage
From within a real python, where SomePackage
is installed globally, but
is not the latest version:
.. tab:: Unix/macOS .. code-block:: console $ python -m pip install --user SomePackage [...] Requirement already satisfied (use --upgrade to upgrade) $ python -m pip install --user --upgrade SomePackage [...] Successfully installed SomePackage
.. tab:: Windows .. code-block:: console C:> py -m pip install --user SomePackage [...] Requirement already satisfied (use --upgrade to upgrade) C:> py -m pip install --user --upgrade SomePackage [...] Successfully installed SomePackage
From within a real python, where SomePackage
is installed globally, and
is the latest version:
.. tab:: Unix/macOS .. code-block:: console $ python -m pip install --user SomePackage [...] Requirement already satisfied (use --upgrade to upgrade) $ python -m pip install --user --upgrade SomePackage [...] Requirement already up-to-date: SomePackage # force the install $ python -m pip install --user --ignore-installed SomePackage [...] Successfully installed SomePackage
.. tab:: Windows .. code-block:: console C:> py -m pip install --user SomePackage [...] Requirement already satisfied (use --upgrade to upgrade) C:> py -m pip install --user --upgrade SomePackage [...] Requirement already up-to-date: SomePackage # force the install C:> py -m pip install --user --ignore-installed SomePackage [...] Successfully installed SomePackage
Ensuring Repeatability
This is now covered in :doc:`../topics/repeatable-installs`.
Fixing conflicting dependencies
This is now covered in :doc:`../topics/dependency-resolution`.
Using pip from your program
As noted previously, pip is a command line program. While it is implemented in
Python, and so is available from your Python code via import pip
, you must
not use pip’s internal APIs in this way. There are a number of reasons for this:
- The pip code assumes that it is in sole control of the global state of the
program.
pip manages things like the logging system configuration, or the values of
the standard IO streams, without considering the possibility that user code
might be affected. - pip’s code is not thread safe. If you were to run pip in a thread, there
is no guarantee that either your code or pip’s would work as you expect. - pip assumes that once it has finished its work, the process will terminate.
It doesn’t need to handle the possibility that other code will continue to
run after that point, so (for example) calling pip twice in the same process
is likely to have issues.
This does not mean that the pip developers are opposed in principle to the idea
that pip could be used as a library — it’s just that this isn’t how it was
written, and it would be a lot of work to redesign the internals for use as a
library, handling all of the above issues, and designing a usable, robust and
stable API that we could guarantee would remain available across multiple
releases of pip. And we simply don’t currently have the resources to even
consider such a task.
What this means in practice is that everything inside of pip is considered an
implementation detail. Even the fact that the import name is pip
is subject
to change without notice. While we do try not to break things as much as
possible, all the internal APIs can change at any time, for any reason. It also
means that we generally won’t fix issues that are a result of using pip in an
unsupported way.
It should also be noted that installing packages into sys.path
in a running
Python process is something that should only be done with care. The import
system caches certain data, and installing new packages while a program is
running may not always behave as expected. In practice, there is rarely an
issue, but it is something to be aware of.
Having said all of the above, it is worth covering the options available if you
decide that you do want to run pip from within your program. The most reliable
approach, and the one that is fully supported, is to run pip in a subprocess.
This is easily done using the standard subprocess
module:
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'my_package'])
If you want to process the output further, use one of the other APIs in the module.
We are using freeze here which outputs installed packages in requirements format.:
reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])
If you don’t want to use pip’s command line functionality, but are rather
trying to implement code that works with Python packages, their metadata, or
PyPI, then you should consider other, supported, packages that offer this type
of ability. Some examples that you could consider include:
packaging
— Utilities to work with standard package metadata (versions,
requirements, etc.)setuptools
(specificallypkg_resources
) — Functions for querying what
packages the user has installed on their system.distlib
— Packaging and distribution utilities (including functions for
interacting with PyPI).
Changes to the pip dependency resolver in 20.3 (2020)
pip 20.3 has a new dependency resolver, on by default for Python 3
users. (pip 20.1 and 20.2 included pre-release versions of the new
dependency resolver, hidden behind optional user flags.) Read below
for a migration guide, how to invoke the legacy resolver, and the
deprecation timeline. We also made a two-minute video explanation
you can watch.
We will continue to improve the pip dependency resolver in response to
testers’ feedback. Please give us feedback through the resolver
testing survey.
Watch out for
The big change in this release is to the pip dependency resolver
within pip.
Computers need to know the right order to install pieces of software
(«to install x
, you need to install y
first»). So, when Python
programmers share software as packages, they have to precisely describe
those installation prerequisites, and pip needs to navigate tricky
situations where it’s getting conflicting instructions. This new
dependency resolver will make pip better at handling that tricky
logic, and make pip easier for you to use and troubleshoot.
The most significant changes to the resolver are:
- It will reduce inconsistency: it will no longer install a
combination of packages that is mutually inconsistent. In older
versions of pip, it is possible for pip to install a package which
does not satisfy the declared requirements of another installed
package. For example, in pip 20.0,pip install "six<1.12"
does the wrong thing, “successfully” installing
"virtualenv==20.0.2"
six==1.11
, even thoughvirtualenv==20.0.2
requires
six>=1.12.0,<2
(defined here).
The new resolver, instead, outright rejects installing anything if it
gets that input. - It will be stricter — if you ask pip to install two packages with
incompatible requirements, it will refuse (rather than installing a
broken combination, like it did in previous versions).
So, if you have been using workarounds to force pip to deal with
incompatible or inconsistent requirements combinations, now’s a good
time to fix the underlying problem in the packages, because pip will
be stricter from here on out.
This also means that, when you run a pip install
command, pip only
considers the packages you are installing in that command, and may
break already-installed packages. It will not guarantee that your
environment will be consistent all the time. If you pip install x
and then pip install y
, it’s possible that the version of y
you get will be different than it would be if you had run pip
in a single command. We are considering changing this
install x y
behavior (per :issue:`7744`) and would like your thoughts on what
pip’s behavior should be; please answer our survey on upgrades that
create conflicts.
We are also changing our support for :ref:`Constraints Files`,
editable installs, and related functionality. We did a fairly
comprehensive overhaul and stripped constraints files down to being
purely a way to specify global (version) limits for packages, and so
some combinations that used to be allowed will now cause
errors. Specifically:
- Constraints don’t override the existing requirements; they simply
constrain what versions are visible as input to the resolver (see
:issue:`9020`) - Providing an editable requirement (
-e .
) does not cause pip to
ignore version specifiers or constraints (see :issue:`8076`), and if
you have a conflict between a pinned requirement and a local
directory then pip will indicate that it cannot find a version
satisfying both (see :issue:`8307`) - Hash-checking mode requires that all requirements are specified as a
==
match on a version and may not work well in combination with
constraints (see :issue:`9020` and :issue:`8792`) - If necessary to satisfy constraints, pip will happily reinstall
packages, upgrading or downgrading, without needing any additional
command-line options (see :issue:`8115` and :doc:`development/architecture/upgrade-options`) - Unnamed requirements are not allowed as constraints (see :issue:`6628` and :issue:`8210`)
- Links are not allowed as constraints (see :issue:`8253`)
- Constraints cannot have extras (see :issue:`6628`)
Per our :ref:`Python 2 Support` policy, pip 20.3 users who are using
Python 2 will use the legacy resolver by default. Python 2 users
should upgrade to Python 3 as soon as possible, since in pip 21.0 in
January 2021, pip dropped support for Python 2 altogether.
How to upgrade and migrate
-
Install pip 20.3 with
python -m pip install --upgrade pip
. -
Validate your current environment by running
pip check
. This
will report if you have any inconsistencies in your set of installed
packages. Having a clean installation will make it much less likely
that you will hit issues with the new resolver (and may
address hidden problems in your current environment!). If you run
pip check
and run into stuff you can’t figure out, please ask
for help in our issue tracker or chat. -
Test the new version of pip.
While we have tried to make sure that pip’s test suite covers as
many cases as we can, we are very aware that there are people using
pip with many different workflows and build processes, and we will
not be able to cover all of those without your help.- If you use pip to install your software, try out the new resolver
and let us know if it works for you withpip install
. Try:- installing several packages simultaneously
- re-creating an environment using a
requirements.txt
file - using
pip install --force-reinstall
to check whether
it does what you think it should - using constraints files
- the «Setups to test with special attention» and «Examples to try» below
- If you have a build pipeline that depends on pip installing your
dependencies for you, check that the new resolver does what you
need. - Run your project’s CI (test suite, build process, etc.) using the
new resolver, and let us know of any issues. - If you have encountered resolver issues with pip in the past,
check whether the new resolver fixes them, and read :ref:`Fixing
conflicting dependencies`. Also, let us know if the new resolver
has issues with any workarounds you put in to address the
current resolver’s limitations. We’ll need to ensure that people
can transition off such workarounds smoothly. - If you develop or support a tool that wraps pip or uses it to
deliver part of your functionality, please test your integration
with pip 20.3.
- If you use pip to install your software, try out the new resolver
-
Troubleshoot and try these workarounds if necessary.
- If pip is taking longer to install packages, read :doc:`Dependency
resolution backtracking <topics/dependency-resolution>` for ways to
reduce the time pip spends backtracking due to dependency conflicts. - If you don’t want pip to actually resolve dependencies, use the
--no-deps
option. This is useful when you have a set of package
versions that work together in reality, even though their metadata says
that they conflict. For guidance on a long-term fix, read
:ref:`Fixing conflicting dependencies`. - If you run into resolution errors and need a workaround while you’re
fixing their root causes, you can choose the old resolver behavior using
the flag--use-deprecated=legacy-resolver
. This will work until we
release pip 21.0 (see
:ref:`Deprecation timeline for 2020 resolver changes`).
- If pip is taking longer to install packages, read :doc:`Dependency
-
Please report bugs through the resolver testing survey.
Setups to test with special attention
- Requirements files with 100+ packages
- Installation workflows that involve multiple requirements files
- Requirements files that include hashes (:ref:`hash-checking mode`)
or pinned dependencies (perhaps as output frompip-compile
within
pip-tools
) - Using :ref:`Constraints Files`
- Continuous integration/continuous deployment setups
- Installing from any kind of version control systems (i.e., Git, Subversion, Mercurial, or CVS), per :doc:`topics/vcs-support`
- Installing from source code held in local directories
Examples to try
Install:
- tensorflow
hacking
pycodestyle
pandas
tablib
elasticsearch
andrequests
togethersix
andcherrypy
togetherpip install flake8-import-order==0.17.1 flake8==3.5.0 --use-feature=2020-resolver
pip install tornado==5.0 sprockets.http==1.5.0 --use-feature=2020-resolver
Try:
pip install
pip uninstall
pip check
pip cache
Tell us about
Specific things we’d love to get feedback on:
- Cases where the new resolver produces the wrong result,
obviously. We hope there won’t be too many of these, but we’d like
to trap such bugs before we remove the legacy resolver. - Cases where the resolver produced an error when you believe it
should have been able to work out what to do. - Cases where the resolver gives an error because there’s a problem
with your requirements, but you need better information to work out
what’s wrong. - If you have workarounds to address issues with the current resolver,
does the new resolver let you remove those workarounds? Tell us!
Please let us know through the resolver testing survey.
Deprecation timeline
We plan for the resolver changeover to proceed as follows, using
:ref:`Feature Flags` and following our :ref:`Release Cadence`:
- pip 20.1: an alpha version of the new resolver was available,
opt-in, using the optional flag
--unstable-feature=resolver
. pip defaulted to legacy
behavior. - pip 20.2: a beta of the new resolver was available, opt-in, using
the flag--use-feature=2020-resolver
. pip defaulted to legacy
behavior. Users of pip 20.2 who want pip to default to using the
new resolver can runpip config set global.use-feature
(for more on that and the alternate
2020-resolver
PIP_USE_FEATURE
environment variable option, see issue
8661). - pip 20.3: pip defaults to the new resolver in Python 3 environments,
but a user can opt-out and choose the old resolver behavior,
using the flag--use-deprecated=legacy-resolver
. In Python 2
environments, pip defaults to the old resolver, and the new one is
available using the flag--use-feature=2020-resolver
. - pip 21.0: pip uses new resolver by default, and the old resolver is
no longer supported. It will be removed after a currently undecided
amount of time, as the removal is dependent on pip’s volunteer
maintainers’ availability. Python 2 support is removed per our
:ref:`Python 2 Support` policy.
Since this work will not change user-visible behavior described in the
pip documentation, this change is not covered by the :ref:`Deprecation
Policy`.
Context and followup
As discussed in our announcement on the PSF blog, the pip team are
in the process of developing a new «dependency resolver» (the part of
pip that works out what to install based on your requirements).
We’re tracking our rollout in :issue:`6536` and you can watch for
announcements on the low-traffic packaging announcements list and
the official Python blog.
Using system trust stores for verifying HTTPS
This is now covered in :doc:`topics/https-certificates`.
Содержание:развернуть
- Pip или pip3?
- Если pip не установлен
-
Windows
-
Linux (Ubuntu и Debian)
-
MacOS
- Как обновить PIP
- Команды PIP
- Пример работы с пакетами
PIP — это менеджер пакетов. Он позволяет устанавливать и управлять пакетами на Python.
Представьте себе ситуацию: вы собираете проект и подключаете множество сторонних библиотек для реализации своей задачи. Если это делать вручную, процесс выглядит примерно так:
- вы заходите на сайт, выбираете нужную версию пакета;
- скачиваете ее, разархивируете, перекидываете в папку проекта;
- подключаете, прописываете пути, тестируете.
Вполне вероятно, что эта версия библиотеки вообще не подходит, и весь процесс повторяется заново. А если таких библиотек 10? Устанавливать их вручную?
Нет 🙅🏻♂️
Менеджер пакетов PIP — решает данную проблему. Весь процесс установки пакета сводится к выполнению консольной команды pip install package-name
. Несложно представить, сколько времени это экономит.
Если вы работали с другими языками программирования, концепция pip может показаться вам знакомой. Pip похож на npm (в Javascript), composer (в PHP) или gem (в Ruby).
Pip является стандартным менеджером пакетов в Python
Pip или pip3?
В зависимости от того, какая версия Python установлена в системе, может потребоваться использовать pip3 вместо pip.
Если вы не знаете какая версия Python установлена на вашей системе, выполните следующие команды:
python --version
— для Python 2.xpython3 --version
— для Python 3.xpython3.8 --version
— для Python 3.8.x
Советуем использовать версию Python 3.6 и выше
Если команда «python» не найдена, установите Python по инструкции из предыдущей статьи.
Далее нужно убедиться, что сам PIP установлен и работает корректно. Узнать это поможет команда:
pip --version
Команда отобразит в консоли версию pip, путь до pip и версию python, для которой в дальнейшем будут устанавливаться пакеты:
pip 19.2.3 from /usr/local/lib/python3.8/site-packages/pip (python 3.8)
☝️ Важный момент: в зависимости от того, какую версию Python вы будете использовать, команда может выглядеть как pip
, pip3
или pip3.8
Альтернативный вариант вызова pip:
python3.7 -m pip install package-name
Флаг -m
сообщает Python-у запустить pip как исполняемый модуль.
Если pip не установлен
Pip поставляется вместе с Python, и доступен после его установки. Если по какой-то причине pip не установлен на вашей системе, установить его будет не сложно.
Windows
- Скачайте файл get-pip.py и сохраните у себя на компьютере.
- Откройте командную строку и перейдите в папку, в которой сохранен
get-pip.py
. - В командной строке выполните команду:
python get-pip.py
илиpython3 get-pip.py
. - PIP установлен 🎉!
Linux (Ubuntu и Debian)
Прежде, чем перейти к непосредственному описанию, хотим отметить, что все команды, описанные ниже, используются от имени root пользователя. Если же вы являетесь обычным пользователем на компьютере, то потребуется использовать команду sudo
, чтобы получить привилегии root.
Для Питона 2-й версии, выполните команду:
apt-get install python-pip
Для Питона 3-ей версии:
apt-get install python3-pip
MacOS
- скачайте файл
get-pip.py
командойcurl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
; - запустите скачанный файл командой:
python get-pip.py
илиpython3 get-pip.py
.
Должна появиться запись Successfully Installed. Процесс закончен, можно приступать к работе с PIP на MacOS!
Как обновить PIP
Иногда, при установке очередного пакета, можно видеть сообщение о том, что доступна новая версия pip.
WARNING: You are using pip version 19.2.3, however version 19.3.1 is available.
А в следующей за ней строке
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
указана команда для обновления pip:
python -m pip install --upgrade pip
Команды PIP
Синтаксис pip выглядит следующим образом: pip + команда + доп. опции
pip <command> [options]
Со всеми командами pip можно ознакомиться, выполнив pip help . Информацию по конкретной команде выведет pip help <command>
.
Рассмотрим команды pip:
pip install package-name
— устанавливает последнюю версию пакета;pip install package-name==4.8.2
— устанавливает пакет версии 4.8.2;pip install package-name --upgrade
— обновляет версию пакета;pip download
— скачивает пакеты;pip uninstall
— удаляет пакеты;pip freeze
— выводит список установленных пакетов в необходимом формате ( обычно используется для записи вrequirements.txt
);pip list
— выводит список установленных пакетов;pip list --outdated
— выводит список устаревших пакетов;pip show
— показывает информацию об установленном пакете;pip check
— проверяет установленные пакеты на совместимость зависимостей;pip search
— по введенному названию, ищет пакеты, опубликованные в PyPI;pip wheel
— собирает wheel-архив по вашим требованиям и зависимостям;pip hash
— вычисляет хеши архивов пакетов;pip completion
— вспомогательная команда используется для завершения основной команды;pip help
— помощь по командам.
Пример работы с пакетами
PIP позволяет устанавливать, обновлять и удалять пакеты на компьютере. Ниже попробуем разобраться с работой менеджера pip на примере парсинга названий свежих статей на сайте habr.com.
- установим нужные пакеты;
- импортируем пакет в свой скрипт;
- разберемся, что такое
requirements.txt
; - обновим/удалим установленные пакеты.
Приступим 🙎🏻♂️
Шаг #1 Установка.
Для начала, нам необходимо установить beautifulsoup4 — библиотеку для парсинга информации с веб-сайтов.
pip3 install beautifulsoup4
pip найдет последнюю версию пакета в официальном репозитории pypi.org. После скачает его со всеми необходимыми зависимостями и установит в вашу систему. Если вам нужно установить определенную версию пакета, укажите её вручную:
pip3 install beautifulsoup4==4.8.2
Данная команда способна даже перезаписать текущую версию на ту, что вы укажите.
Также для работы beautifulsoup нам понадобится пакет lxml:
pip install lxml
☝️ Важный момент: по умолчанию pip устанавливает пакеты глобально. Это может привести к конфликтам между версиями пакетов. На практике, чтобы изолировать пакеты текущего проекта, создают виртуальное окружение (virtualenv).
Шаг #2 Импортирование в скрипте.
Для того чтобы воспользоваться функционалом установленного пакета, подключим его в наш скрипт, и напишем простой парсер:
from urllib.request import urlopen
from bs4 import BeautifulSoup
# скачиваем html
page = urlopen("https://habr.com/ru/top/")
content = page.read()
# сохраняем html в виде объекта BeautifulSoup
soup = BeautifulSoup(content, "lxml")
# Находим все теги "a" с классом "post__title_link"
all_a_titles = soup.findAll("a", { "class" : "post__title_link" })
# Проходим по каждому найденному тегу и выводим на экран название статьи
for a_title in all_a_titles:
print(a_title.text)
Шаг #3 requirements.txt.
Если вы просматривали какие-либо проекты Python на Github или где-либо еще, вы, вероятно, заметили файл под названием requirements.txt. Этот файл используется для указания того, какие пакеты необходимы для запуска проекта (в нашем случае beautifulsoup4 и lxml).
Файл requirements.txt
создается командой:
pip freeze > requirements.txt
и выглядит следующим образом:
beautifulsoup4==4.8.2
lxml==4.4.2
soupsieve==1.9.5
Теперь ваш скрипт вместе с файлом requirements.txt можно сохранить в системе контроля версий (например git).
Для работы парсера в новом месте (например на компьютере другого разработчика или на удаленном сервере) необходимо затянуть файлы из системы контроля версий и выполнить команду:
pip install -r requirements.txt
Шаг #4 Обновление/удаление установленных пакетов.
Команда pip list --outdated
выведет список всех устаревших пакетов. Обновить отдельно выбранный пакет поможет команда:
pip install package-name --upgrade
Однако бывают ситуации, когда нужно обновить сразу все пакеты из requirements.txt. Достаточно выполнить команду:
pip install -r requirements.txt --upgrade
Для удаления пакета выполните:
pip uninstall package-name
Для удаления всех пакетов из requirements.txt:
pip uninstall -r requirements.txt -y
Мы разобрали основы по работе с PIP. Как правило, этого достаточно для работы с большей частью проектов.
List of content you will read in this article:
- 1. What is Python? [Definition]
- 2. How to Upgrade pip in Windows/Linux?
- 3. How to Downgrade pip?
- 4. How to install Python packages with pip?
- 5. How to update Python packages with pip?
- 6. How to uninstall Python packages with pip?
- 7. How to Install PIP [Step-by-Step Guide to Upgrade PIP Packages]
- 8. Conclusion
Pip is a great tool for installing and managing Python packages; it is a package manager that allows the installation of third-party software packages for Python. It is among the most powerful package managers for Python and has become quite popular because it is quite easy to use. Even though most Python versions come pre-loaded with it, this guide will teach you to manually install pip, review its version, and use some simple pip commands. It is a preinstall package with python to only update or package versions. It does not play any role in the installation or uninstallation of Python.
What is Python? [Definition]
Python is an open-source programming language that allows software development and even makes a great choice for web development. Also, one can use Python on several popular operating systems, including Windows, Linux, and iOS.
How to Upgrade pip in Windows/Linux?
To take advantage of the new features and security patches, update pip from time to time, just like any other software. While pip can automatically update itself, you need to know how to update pip on windows and Linux VPS manually. Follow the below steps to update pip.
Step 1: Simply open Command Prompt on the Windows system or terminal in Linux.
For Windows: First, enter Windows+R and type CMD and enter, or you can open the Windows search box, then type command prompt and enter button.
For Mac: press command + space key, type terminal, and hit the enter button.
For Linux: just log in to ssh with putty or any other terminal software.
Step 2: Execute the following command:
python -m pip install --upgrade pip
This will uninstall the current version of pip on the system and replace it with the latest version.
How to Downgrade pip?
If one needs to revert to a previous version of pip due to compatibility issues, one can easily do it from the Command Prompt. Open a command prompt and type the following command to downgrade to a custom version of pip (specify the version of pip).
python -m pip install pip==18.0 (or any other version)
Pip will be downgraded to the specified version. After the execution of the above command, one can check the pip version with this command: pip3 —version.
How to install Python packages with pip?
With pip, we can install any new package for our Python environment. To install a new third-party package using pip, we can use the pip install <package name> command. And pip will install the new packages from the PyPI repository.
Let’s say if you want to install NumPy for your Python environment, you can run the following pip install command.
$ pip3 install numpy
Or
$ pip install numpy
How to update Python packages with pip?
After installing the package, later, if we wish to update the package to the latest version. For that also we can take the help of pip command.
With pip3 install —upgrade <package name> command, we can upgrade the installed python package to the latest available version.
For example, let’s say we want to upgrade the installed NumPy package to its latest version.
$ pip3 install --upgrade numpy
Or
$ pip install --upgrade numpy
How to uninstall Python packages with pip?
We can also uninstall an installed python package using the pip command. The pip command makes it very easy for the developer to manage the third-party packages. For some reason, if you do not want a specific package for your Python environment, there you can use the following pip command to uninstall the package.
pip3 uninstall <package_name>
Let’s say now you do not need the installed NumPy package and wish to uninstall it. For that, you can run the following command on your terminal or command prompt.
pip3 uninstall numpy
Or
pip uninstall <package_name>
How to Install PIP [Step-by-Step Guide to Upgrade PIP Packages]
Here are some simple steps that guide you to installing pip on the system:
Step 1: Install Python and pip
To install pip for your system, you first need to install Python3. And to install Python, you can visit the official website of Python(recommended for windows and mac). If you are on windows and mac, with the latest installation of Python, pip will also get pre-installed.
If you are a Linux user, you can install the latest version of Python and pip from the terminal only rather than installing Python from its official site.
Linux installs Python and pip (with sudo access).
$ sudo apt update
$sudo apt install python3 python3-pip
The above two commands will install Python for your Linux system.
Step 2: Check the pip Version and Verify the Installation
To check if pip is installed correctly, run the following command in the command prompt (for Windows) or Terminal (for Linux and macOS):
pip3 --version
Or
pip --version
You will get an output similar to the one shown below:
pip18.0 from c:usersadministratorappdatalocalprogramspythonpython37libsite-packagepip (python 3.7)
Step 3: Managing Python Packages with pip
Use pip to handle functionalities once it’s installed and configured in the system. To get a quick overview of the functions and syntax available for Pip, open a command prompt and type:
pip3 help
Or
pip help
If you have an older version of Python already installed in your operating system, then you can check out our blog on how to update python for a deeper understanding of how to install pip in windows/Linux, This blog post will help you.
Conclusion
We hope we have successfully made you understand how to install pip on your system. If you are working with Python development, pip can come in handy for managing various python library packages. Also, you can easily choose a pip version that you want to work with.
People Are Also Reading:
- How to Learn Python
- How to Update Python Version?
- How to Install Python on Windows
- Linux Commands Cheat Sheet
- What is the CLI?
В процессе разработки программного обеспечения на Python часто возникает необходимость воспользоваться пакетом, который в данный момент отсутствует на вашем компьютере. О том, откуда взять нужный вам пакет и как его установить, вы узнаете из этого урока.
- Где взять отсутствующий пакет?
- Менеджер пакетов в Python – pip
- Установка pip
- Обновление pip
- Использование pip
- Установка пакета
- Удаление пакета
- Обновление пакетов
- Просмотр установленных пакетов
- Поиск пакета в репозитории
- Где еще можно почитать про работу с pip?
Где взять отсутствующий пакет?
Необходимость в установке дополнительного пакета возникнет очень быстро, если вы решите поработать над задачей, за рамками базового функционала, который предоставляет Python. Например: работа с web, обработка изображений, криптография и т.п. В этом случае, необходимо узнать, какой пакет содержит функционал, который вам необходим, найти его, скачать, разместить в нужном каталоге и начать использовать. Все эти действия можно сделать вручную, но этот процесс поддается автоматизации. К тому же скачивать пакеты с неизвестных сайтов может быть довольно опасно.
К счастью для нас, в рамках Python, все эти задачи решены. Существует так называемый Python Package Index (PyPI) – это репозиторий, открытый для всех Python разработчиков, в нем вы можете найти пакеты для решения практически любых задач. Там также есть возможность выкладывать свои пакеты. Для скачивания и установки используется специальная утилита, которая называется pip.
Менеджер пакетов в Python – pip
Pip – это консольная утилита (без графического интерфейса). После того, как вы ее скачаете и установите, она пропишется в PATH и будет доступна для использования.
Эту утилиту можно запускать как самостоятельно:
> pip <аргументы>
так и через интерпретатор Python:
> python -m pip <аргументы>
Ключ -m означает, что мы хотим запустить модуль (в данном случае pip). Более подробно о том, как использовать pip, вы сможете прочитать ниже.
Установка pip
При развертывании современной версии Python (начиная с Python 2.7.9 и Python 3.4),
pip устанавливается автоматически. Но если, по какой-то причине, pip не установлен на вашем ПК, то сделать это можно вручную. Существует несколько способов.
Универсальный способ
Будем считать, что Python у вас уже установлен, теперь необходимо установить pip. Для того, чтобы это сделать, скачайте скрипт get-pip.py
> curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
и выполните его.
> python get-pip.py
При этом, вместе с pip будут установлены setuptools и wheels. Setuptools – это набор инструментов для построения пакетов Python. Wheels – это формат дистрибутива для пакета Python. Обсуждение этих составляющих выходит за рамки урока, поэтому мы не будем на них останавливаться.
Способ для Linux
Если вы используете Linux, то для установки pip можно воспользоваться имеющимся в вашем дистрибутиве пакетным менеджером. Ниже будут перечислены команды для ряда Linux систем, запускающие установку pip (будем рассматривать только Python 3, т.к. Python 2 уже морально устарел, а его поддержка и развитие будут прекращены после 2020 года).
Fedora
Fedora 21:
> sudo yum install python3 python3-wheel
Fedora 22:
> sudo dnf install python3 python3-wheel
openSUSE
> sudo zypper install python3-pip python3-setuptools python3-wheel
Debian/Ubuntu
> sudo apt install python3-venv python3-pip
Arch Linux
> sudo pacman -S python-pip
Обновление pip
Если вы работаете с Linux, то для обновления pip запустите следующую команду.
> pip install -U pip
Для Windows команда будет следующей:
> python -m pip install -U pip
Использование pip
Далее рассмотрим основные варианты использования pip: установка пакетов, удаление и обновление пакетов.
Установка пакета
Pip позволяет установить самую последнюю версию пакета, конкретную версию или воспользоваться логическим выражением, через которое можно определить, что вам, например, нужна версия не ниже указанной. Также есть поддержка установки пакетов из репозитория. Рассмотрим, как использовать эти варианты.
Установка последней версии пакета
> pip install ProjectName
Установка определенной версии
> pip install ProjectName==3.2
Установка пакета с версией не ниже 3.1
> pip install ProjectName>=3.1
Установка Python пакета из git репозитория
> pip install -e git+https://gitrepo.com/ProjectName.git
Установка из альтернативного индекса
> pip install --index-url http://pypackage.com/ ProjectName
Установка пакета из локальной директории
> pip install ./dist/ProjectName.tar.gz
Удаление пакета
Для того, чтобы удалить пакет воспользуйтесь командой
> pip uninstall ProjectName
Обновление пакетов
Для обновления пакета используйте ключ –upgrade.
> pip install --upgrade ProjectName
Просмотр установленных пакетов
Для вывода списка всех установленных пакетов применяется команда pip list.
> pip list
Если вы хотите получить более подробную информацию о конкретном пакете, то используйте аргумент show.
> pip show ProjectName
Поиск пакета в репозитории
Если вы не знаете точное название пакета, или хотите посмотреть на пакеты, содержащие конкретное слово, то вы можете это сделать, используя аргумент search.
> pip search "test"
Где ещё можно прочитать про работу с pip?
В сети довольно много информации по работе с данной утилитой.
Python Packaging User Guide – набор различных руководств по работе с пакетами в Python
Документация по pip.
Статья на Geekbrains.
P.S.
Если вам интересна тема анализа данных, то мы рекомендуем ознакомиться с библиотекой Pandas. На нашем сайте вы можете найти вводные уроки по этой теме. Все уроки по библиотеке Pandas собраны в книге “Pandas. Работа с данными”.
<<< Python. Урок 15. Итераторы и генераторы Python. Урок 17. Виртуальные окружения>>>
Renesh Bedre
6 minute read
- pip is Python’s official package manager and is a recommended method for installing, upgrading, and
uninstalling the Python packages.
- Check below how to install and upgrade the pip on Windows, Linux, and macOS for managing the Python packages
Installing and upgrading pip
pip
is a package (bundle of software) installer for Python.- In order to use
pip
, it is required to install Python (Python 3 >=3.4). You can check here
for installing Python 3 on Windows, Linux, and macOS from the source. Additionally, you can also check the Python installation
guide for installing Python from OS specific package manager.
Note: If you have installed Python 3 from the source, you should add the Python executable in the system path variable
to be able to run Python commands from any path in OS. Check how to add Python executable in system path variable for
Windows, Linux, and macOS
Learn more about Linux basic commands for beginners
Check pip version
- If you have already installed Python 3 (>=3.4), you can run the below shell command to check the
pip
version - If you get error as “ ‘pip’ is not recognized as an internal or external command “ on Windows, then you need to
add pip installation directory to the system variable (check here how to do this)
# Windows, Linux, and macOS
# using pip
pip --version
# output if installed
pip 22.3.1
python -m pip --version
# output if installed
pip 22.3.1
If pip is not installed, use ensurepip to install pip (see below)
Install pip using ensurepip, conda, or get-pip.py script
# Windows, Linux, and macOS
python -m ensurepip --default-pip
# within conda environment
conda install pip
To install using get-pip.py
, first download the script and run following
command,
# Windows, Linux, and macOS
python get-pip.py
To install on Ubuntu, use the following command
# Ubuntu Linux
sudo apt update
sudo apt install python3-pip
upgrading pip to the latest version
# Windows, Linux, and macOS
# using pip
pip install --upgrade pip
# using Python
python -m pip install --upgrade pip
Installing a specific version of pip
# Windows, Linux, and macOS
# using pip
pip install --upgrade pip==21.0.1
# using Python
python -m pip install --upgrade pip==21.0.1
# using easy_install (deprecated)
easy_install pip==21.0.1
Installing and upgrading Python packages using pip
Installing Python packages
# Windows, Linux, and macOS
# using pip (replace bioinfokit with required python package name)
pip install bioinfokit
# using Python
python -m pip install bioinfokit
pip
should be used for installing or upgrading Python packages and it is not ideal for installing or upgrading
Python. If you want install or upgrade Python, you download the latest version of Python
and install them. In addition, you can also package manager for Linux (e.g. APT) or macOS (e.g. Homebrew) for installing
or upgrading Python.
Upgrading installed Python packages to the latest version
# Windows, Linux, and macOS
# using pip (replace bioinfokit with required python package name)
pip install --upgrade bioinfokit
# using Python
python -m pip install --upgrade bioinfokit
# upgrade all installed packages at same time using pip-review (need to install pip-review package)
pip-review --auto
Install a specific version of Python packages
General syntax to install the specific version of Python packages is pip install <python_package_name>==<version>
. If
you don’t specify the version, the latest version of the Python package will be installed.
If you want to install the older version, you need to provide the specific version of Python package. For example,
to install the 1.22.0 version of NumPy, use the command as pip install numpy==1.22.0
See more examples,
# Windows, Linux, and macOS
# using pip (replace bioinfokit with required python package name)
pip install bioinfokit==2.0.0
# using Python
python -m pip install bioinfokit==2.0.0
Install specific packages from requirements file
- requirements file (
requirements.txt
) let you install the multiple Python packages with specific or latest versions
at once - requirements file (requirements.txt) contains the name
of Python packages that need to be installed
# Windows, Linux, and macOS
# using pip
pip install -r requirements.txt
# using Python
python -m pip install -r requirements.txt
Uninstall Python packages
# Windows, Linux, and macOS
# using pip (replace bioinfokit with required python package name)
pip uninstall bioinfokit
# using Python
python -m pip uninstall bioinfokit
Check Python package version
# Windows, Linux, and macOS
# using pip (replace bioinfokit with required python package name)
pip show bioinfokit
# output
Name: bioinfokit
Version: 2.0.4
...
pip freeze # it will list all installed packages with their version
# output
adjustText==0.7.3
bioinfokit==2.0.4
...
# using Python
python -c "import bioinfokit; print(bioinfokit.__version__)"
2.0.4
# using Python interpreter
import bioinfokit
bioinfokit.__version__
'2.0.4'
Installing and upgrading Python packages using conda
In addition to pip
, you can also use the conda
package manager for managing the Python packages. In addition to managing package dependencies, conda
can create
multiple environments for managing package requirements for different projects.
Installing Python packages using conda
,
# Windows, Linux, and macOS
conda install -c conda-forge numpy # same as conda install numpy
Conda stores packages in channels and installs them from default channels. If the package is not in the default
channel, you should provide the channel name (e.g.-c bioconda
) to install it. You can find the packages and their
channels in the conda public repository.
Upgrading Python packages using conda
,
# Windows, Linux, and macOS
conda update numpy
Installing specific version of Python packages using conda
,
# Windows, Linux, and macOS
conda install numpy=1.23.0
Virtual environments to install Python packages
- When you have multiple applications to run and each application has a specific requirement of Python packages, then
running those multiple applications with one Python installation is not convenient. For example, if one application
needs v1.0 of a specific Python package and another application needs v2.0 of the same Python package. - In such situations, the virtual environment is a helpful tool to install the specific versions of Python packages
required for each application. You can use either Python or conda to create virtual environment.
Create and activate a virtual environment
# using Python3
python -m venv example_venv
# using conda
conda create --name example_venv
To use a virtual environment, you need to first activate it
# Linux and macOS
source example_venv/bin/activate
# Windows
example_venv/Scripts/activate
# for virtual environment created using conda
conda activate example_venv
Once virtual environment is activated, you should see virtual environment name (example_venv) on your command prompt
Installing Python packages in a virtual environment
Once the virtual environment is activated, you can install the specific Python packages as discussed in the previous section
Enhance your skills with courses on Python
- Python for Data Science, AI & Development
- Python 3 Programming Specialization
- Python for Everybody Specialization
- Data Analysis Using Python
- Python for Genomic Data Science
References
- Installing Packages
- pip
- Virtual Environments and Packages
If you have any questions, comments or recommendations, please email me at
reneshbe@gmail.com
If you enhanced your knowledge and practical skills from this article, consider supporting me on
This work is licensed under a Creative Commons Attribution 4.0 International License
Some of the links on this page may be affiliate links, which means we may get an affiliate commission on a valid purchase.
The retailer will pay the commission at no additional cost to you.
Users and developers of Python are probably familiar with PIP. It is the official package installer for Python and can be used to install packages that are not included with the standard Python distribution. You can use pip
to install packages that have been published in the official Python Package Index (PyPI) as well as other indexes.
Many users question exactly just how to upgrade to the latest version of PIP, given the ever-evolving and fast-moving python ecosystem. The short answer is, pip
is just like any other PyPI package and you can upgrade it to newer (or downgrade to older) versions, just as you would upgrade or downgrade any other package.
Related: How to install pip
on Windows, macOS & Linux
How To Install PIP On MacOS, Windows & Linux
Pip is a standard package manager for installing and maintaining Python packages. A variety of built-in functions and packages are included in the Python standard library, but some non-standard ones need to be downloaded and pip can help you do just that. Related: How to upgrade pip in Windows, MacO…
The UptideThe Uptide
TL;DR
# Windows Command Prompt
> python -m pip install --upgrade pip
# Linux Terminal
$ pip install --upgrade pip
# MacOS Terminal
$ pip install --upgrade pip
How To Update Your Version Of Pip In Windows
On Windows, you can upgrade pip by opening the Command Prompt, and typing the following command:
python -m pip install --upgrade pip
An important thing to note is that this command will only work if you have successfully managed to add Python to Windows path. If you haven’t done so, you might get the following error in your command prompt:
> ‘pip’ is not recognized as an internal
> or external command, operable program or batch file
If this error does occur, you must first add Python to Windows path and then update your PIP version.
Upgrade Or Downgrade Pip To A Specific Version on Windows
If you want to upgrade or downgrade Pip to an exact version, there is a way to do that. If you know which version you want, just add a flag: pip==<version>
to the command above.
For example, if you want to downgrade to version 19.2, the final command would look something like this,
> python -m pip install pip==19.2
How To Update Your Version Of Pip In Linux
The process of updating pip
in Linux is pretty straightforward. The first thing you need to do is to check your version of pip typing the following command:
$ pip --version
Once you know your current version and you are sure that you want to upgrade, you can use the pip install upgrade command in the terminal and hit enter.
$ pip install -U pip
or
$ pip install --upgrade pip
This will upgrade your pip version to the latest.
If you run into permission issues, you may also try the following commands. When you use sudo
you might also have to enter your root password.
$ sudo -H pip3 install --upgrade pip
$ sudo -H pip2 install --upgrade pip
How To Update Your Version Of Pip In MacOS
The command to upgrade PIP on MacOS is the same as in Linux.
$ pip install --upgrade pip
If you get an error: pip command not found
, you can instead use the following command:
$ python -m pip install --upgrade pip
Note, these commands also work for pip3. Moreover, if you have pip3 installed, you can use the pip3 alias and it will work the same way.
$ pip3 install --upgrade pip
Upgrade Or Downgrade To Specific Pip Version
If you want to upgrade or downgrade your version of pip to a specific version on a Mac, you can do this by adding a pip==<version>
flag to the end of your update command.
$ pip3 install --upgrade pip==20.2.2
or
$ pip install --upgrade pip==20.2.2
When using Python, it is important to make sure to keep your dependencies up to date, and this goes for versions of pip
as well. This guide will make sure that you are always on the right version no matter what your operating system is.