Как установить pip для python на windows

The Python package installer. Contribute to pypa/pip development by creating an account on GitHub.

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
    and no_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:

  1. 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 when pip 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
    
    
  2. 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. if pkg1 requires
    pkg3>=1.0 and pkg2 requires pkg3>=1.0,<=2.0, and if pkg1 is
    resolved first, pip will only use pkg3>=1.0, and could easily end up
    installing a version of pkg3 that conflicts with the needs of pkg2.
    To solve this problem, you can place pkg3>=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
    
  3. Requirements files are used to force pip to install an alternate version of a
    sub-dependency. For example, suppose ProjectA in your requirements file
    requires ProjectB, but the latest version (v1.3) has a bug, you can force
    pip to accept earlier versions like so:

    ProjectA
    ProjectB<1.3
    
  4. 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 requirements
  • only-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 existing SomePackage or
    SomeDependency.
  • pip install --upgrade SomePackage: will upgrade SomePackage, but not
    SomeDependency (unless a minimum requirement is not met).
  • pip install --upgrade SomePackage --upgrade-strategy=eager: upgrades both
    SomePackage and SomeDependency.

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:

  1. When globally installed packages are on the python path, and they conflict
    with the installation requirements, they are ignored, and not
    uninstalled.
  2. 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).
  3. 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.
  4. 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:

  1. 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.
  2. 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.
  3. 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 (specifically pkg_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"
    "virtualenv==20.0.2"
    does the wrong thing, “successfully” installing
    six==1.11, even though virtualenv==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
install x y
in a single command. We are considering changing this
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

  1. Install pip 20.3 with python -m pip install --upgrade pip.

  2. 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.

  3. 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 with pip 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.
  4. 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`).
  5. 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 from pip-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 and requests together
  • six and cherrypy together
  • pip 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 run pip config set global.use-feature
    2020-resolver
    (for more on that and the alternate
    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`.

Python 3.4+ and 2.7.9+

Good news! Python 3.4 (released March 2014) and Python 2.7.9 (released December 2014) ship with Pip. This is the best feature of any Python release. It makes the community’s wealth of libraries accessible to everyone. Newbies are no longer excluded from using community libraries by the prohibitive difficulty of setup. In shipping with a package manager, Python joins Ruby, Node.js, Haskell, Perl, Go—almost every other contemporary language with a majority open-source community. Thank you, Python.

If you do find that pip is not available, simply run ensurepip.

  • On Windows:

    py -3 -m ensurepip
    
  • Otherwise:

    python3 -m ensurepip
    

Of course, that doesn’t mean Python packaging is problem solved. The experience remains frustrating. I discuss this in the Stack Overflow question Does Python have a package/module management system?.

Python 3 ≤ 3.3 and 2 ≤ 2.7.8

Flying in the face of its ‘batteries included’ motto, Python ships without a package manager. To make matters worse, Pip was—until recently—ironically difficult to install.

Official instructions

Per https://pip.pypa.io/en/stable/installing/#do-i-need-to-install-pip:

Download get-pip.py, being careful to save it as a .py file rather than .txt. Then, run it from the command prompt:

python get-pip.py

You possibly need an administrator command prompt to do this. Follow Start a Command Prompt as an Administrator (Microsoft TechNet).

This installs the pip package, which (in Windows) contains …Scriptspip.exe that path must be in PATH environment variable to use pip from the command line (see the second part of ‘Alternative Instructions’ for adding it to your PATH,

Alternative instructions

The official documentation tells users to install Pip and each of its dependencies from source. That’s tedious for the experienced and prohibitively difficult for newbies.

For our sake, Christoph Gohlke prepares Windows installers (.msi) for popular Python packages. He builds installers for all Python versions, both 32 and 64 bit. You need to:

  1. Install setuptools
  2. Install pip

For me, this installed Pip at C:Python27Scriptspip.exe. Find pip.exe on your computer, then add its folder (for example, C:Python27Scripts) to your path (Start / Edit environment variables). Now you should be able to run pip from the command line. Try installing a package:

pip install httpie

There you go (hopefully)! Solutions for common problems are given below:

Proxy problems

If you work in an office, you might be behind an HTTP proxy. If so, set the environment variables http_proxy and https_proxy. Most Python applications (and other free software) respect these. Example syntax:

http://proxy_url:port
http://username:password@proxy_url:port

If you’re really unlucky, your proxy might be a Microsoft NTLM proxy. Free software can’t cope. The only solution is to install a free software friendly proxy that forwards to the nasty proxy. http://cntlm.sourceforge.net/

Unable to find vcvarsall.bat

Python modules can be partly written in C or C++. Pip tries to compile from source. If you don’t have a C/C++ compiler installed and configured, you’ll see this cryptic error message.

Error: Unable to find vcvarsall.bat

You can fix that by installing a C++ compiler such as MinGW or Visual C++. Microsoft actually ships one specifically for use with Python. Or try Microsoft Visual C++ Compiler for Python 2.7.

Often though it’s easier to check Christoph’s site for your package.

Python — очень популярный язык программирования. Именно поэтому он поддерживает множество дополнительных фреймворков и библиотек. Сторонние фреймворки устанавливаются, чтобы каждый раз не изобретать велосипед, а пользоваться уже готовыми и проверенными решениями. Но прежде чем установить требуемый пакет на Python, этот программный пакет еще нужно найти. Здесь поможет центральный репозиторий Питона —PyPI, он же Python Package Index, он же каталог Python-пакетов.

Но тут возникает небольшая проблема, так как скачивание, installing и работа с пакетами в ручном режиме — занятие довольно утомительное и небыстрое. Однако этих трудностей можно избежать, если использовать для инсталляции специальный инструмент, который называют PIP. С его помощью процесс упрощается и ускоряется.

Речь идет об утилите командной строки, позволяющей инсталлировать и деинсталлировать программные пакеты PyPI с помощью простейшей команды pip. Еще PIP («пип») называют системой управления программными пакетами, написанными на языке Python. Подразумеваются пакеты, которые находятся в центральном репозитории PyPI.

Чаще всего работа с PIP не вызывает проблем, особенно если у пользователя уже есть опыт работы с терминалом в операционной системе Windows, Linux, Mac.

Также стоит отметить, что для Python серии 3.4 и выше PIP уже установлен (installed), так как он устанавливается (installs) по умолчанию одновременно с Пайтоном. Именно поэтому для начала надо проверить версию Python, которая есть на компьютере. Седлать это несложно: просто запустите в терминале следующую команду:

 python --version

Эта команда работает для Windows и Mac. Если у пользователя установлена операционная система Linux, то команда для Python 2 будет аналогичной, а вот для версии 3 будет немного отличаться:

python3 --version

Для тех, кто забыл: для запуска терминала командной строки нужно выполнить простые действия:

  • для Windows — комбинация клавиш Win+X;
  • для Mac — Command+пробел;
  • для Linux — Ctrl+Alt+T (возможны различия в зависимости от установленного дистрибутива).

После выполнения вышеописанных действий пользователь получит информацию о текущей версии Питона, установленной в его операционной системе. Для Виндовс это может выглядеть следующим образом:

Если вы получили аналогичный результат, Python готов к работе. Если нет, его необходимо сначала установить (когда Пайтон не установлен, выдается сообщение «Python is not defined»).

Особенности PIP install для Python 3 на Windows

Ниже представлен алгоритм установки PIP для Пайтон 3. Этот алгоритм подходит, если на компьютере пользователя установлена ОС Windows 7/8.1/10.

Порядок действий:

  1. Скачивается инсталляционный скрипт get-pip.py. Для этого надо перейти по ссылке, нажать правой кнопкой мыши на любую часть экрана и выполнить «Сохранить как…». Скрипт можно сохранять в любую папку на усмотрение пользователя. Пусть это будет, к примеру, папка «Загрузки».
  2. Открывается командная строка и осуществляется переход к каталогу, куда скачан файлом get-pip.py (в нашем случае это папка «Загрузки», но может быть и любая другая).

На картинке выше был открыт терминал, потом выполнен переход в папку «Загрузки» (использовалась команда cd). Просмотрев содержимое директории с помощью команды dir, мы удостоверились в том, что скрипт (файл) с именем get-pip и расширением .py в этой папке присутствует.

3. Запускается команда: python get-pip.py

Устанавливаем PIP на Mac

В последних версиях операционной системы Mac как Python, так и PIP уже установлены. Однако команда инсталляции через терминал все же существует:

sudo easy_install pip

Также можно воспользоваться утилитой командной строки Homebrew (она тоже должна быть установлена):

brew install python

Установка на Linux

Если пользователю достался Линукс-дистрибутив с предустановленным языком программирования Python3, получить PIP можно с помощью системного менеджера пакетов — это более практичный и эффективный способ.

Для Python3 и Advanced Package Tool это выглядит следующим образом:

sudo apt-get install python3-pip

Команды для других пакетных менеджеров —  в списке ниже:

Обновление PIP для Python

Обновление позволяет всегда иметь свежую версию. Это важно с точки зрения безопасности.

Обновление PIP трудностей не вызывает. Для Windows все просто:

python -m pip install -U pip

Не менее сложен процесс и для операционных систем Mac и Linux:

pip install -U pip

Если разговор идет о текущих версиях Linux, нужна команда pip3.

Как работает PIP?

Когда все выполнено правильно, система готова к работе и позволят устанавливать программные пакеты pip (библиотеки, фреймворки) непосредственно из репозитория PyPI:

pip install package-name

При необходимости можно установить и конкретную версию интересующего пакета (а не последнюю, как это происходит по умолчанию):

pip install package-name==1.0.0

Также можно выполнить поиск определенного пакета:

pip search "your_query"

Или посмотреть детали о пакете, который уже инсталлирован:

pip show package-name

Вдобавок к этому, есть вероятность просмотра всех инсталлированных программных пакетов:

pip list

Удаление тоже не вызывает затруднений:

pip uninstall package-name

Пример

Команды ниже производят установку известнейшей Пайтон-библиотеки с открытым исходным кодом NumPy:

Для Линукс:

sudo pip3 install numpy

Для Виндовс:

pip3 install numpy

Если команда выше не сработает, можно обратиться к утилите напрямую:

Python wheels

Выше была рассмотрена работа с зависимыми Python-пакетами и их установка посредством pip из PyPI. Однако некоторые специалисты утверждают, что этот подход имеет свои минусы:

  1. Оказывается влияние на производительность — пользователю постоянно нужно скачивать и выполнять сборку пакетов, что тоже не всегда быстро.
  2. Работа осуществляется онлайн — если с интернетом проблемы, инсталляция не произойдет.
  3. Стабильность и надежность могут оказаться под вопросом — утверждение справедливо, если:

— возникают проблемы и неполадки на стороне PyPI;

— возникают нарушения зависимостей (некоторые нужные пользователю пакеты удаляются из PyPI);

— возникают неполадки у хостингового провайдера, способные привести к недоступности сетевых ресурсов, того же PyPI.

Избежать всех этих проблем можно путем применения заранее подготовленных пакетов wheel для всех интересующих зависимостей и хранения их в системном репозитории.

Для справки: Wheel — современный формат распространения пакетов в среде Python (wheel пришел на замену eggs). Подробнее об этом можете почитать здесь.

При подготовке статьи использовались следующие источники:

  • https://dizballanze.com/ru/python-wheels-dlia-bystroi-ustanovki-zavisimostei/;
  • https://pythonworld.ru/osnovy/pip.html;
  • https://pythonru.com/baza-znanij/ustanovka-pip-dlja-python-i-bazovye-komandy.

Как любой серьёзный язык программирования, Python поддерживает сторонние библиотеки и фреймворки. Их устанавливают, чтобы не изобретать колесо в каждом новом проекте. Необходимы пакеты можно найти в центральном репозитории Python — PyPI (Python Package Index — каталог пакетов Python).

Однако скачивание, установка и работа с этими пакетами вручную утомительны и занимают много времени. Именно поэтому многие разработчики полагаются на специальный инструмент PIP для Python, который всё делает гораздо быстрее и проще.

Сама аббревиатура — рекурсивный акроним, который на русском звучит как “PIP установщик пакетов” или “Предпочитаемый установщик программ”. Это утилита командной строки, которая позволяет устанавливать, переустанавливать и деинсталлировать PyPI пакеты простой командой pip.

Если вы когда-нибудь работали с командной строкой Windows и с терминалом на Linux или Mac и чувствуете себя уверенно, можете пропустить инструкции по установке.

Устанавливается ли PIP вместе с Python?

Если вы пользуетесь Python 2.7.9 (и выше) или Python 3.4 (и выше), PIP устанавливается вместе с Python по умолчанию. Если же у вас более старая версия Python, то сначала ознакомьтесь с инструкцией по установке.

Правильно ли Python установлен?

Вы должны быть уверены, что Python должным образом установлен на вашей системе. На Windows откройте командную строку с помощью комбинации Win+X. На Mac запустите терминал с помощью Command+пробел, а на Linux – комбинацией Ctrl+Alt+T или как-то иначе именно для вашего дистрибутива.

Затем введите команду:

python --version

На Linux пользователям Python 3.x следует ввести:

python3 --version

Если вы получили номер версии (например, Python 2.7.5), значит Python готов к использованию.

Если вы получили сообщение Python is not defined (Python не установлен), значит, для начала вам следует установить Python. Это уже не по теме статьи. Подробные инструкции по установке Python читайте в теме: Скачать и установить Python.

Как установить PIP на Windows.

Следующие инструкции подойдут для Windows 7, Windows 8.1 и Windows 10.

  1. Скачайте установочный скрипт get-pip.py. Если у вас Python 3.2, версия get-pip.py должны быть такой же. В любом случае щелкайте правой кнопкой мыши на ссылке и нажмите “Сохранить как…” и сохраните скрипт в любую безопасную папку, например в “Загрузки”.
  2. Откройте командную строку и перейдите к каталогу с файлом get-pip.py.
  3. Запустите следующую команду: 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

Installing with get-pip.py¶

To install pip, securely download get-pip.py. [1]:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Inspect get-pip.py for any malevolence. Then run the following:

Warning

Be cautious if you are using a Python install that is managed by your operating
system or another package manager. get-pip.py does not coordinate with
those tools, and may leave your system in an inconsistent state.

get-pip.py also installs setuptools [2] and wheel
if they are not already. setuptools is required to install
source distributions. Both are
required in order to build a Wheel Cache (which improves installation
speed), although neither are required to install pre-built wheels.

Note

The get-pip.py script is supported on the same python version as pip.
For the now unsupported Python 2.6, alternate script is available
here.

get-pip.py options¶

--no-setuptools

If set, do not attempt to install setuptools

--no-wheel

If set, do not attempt to install wheel

get-pip.py allows pip install options and the general options. Below are
some examples:

Install from local copies of pip and setuptools:

python get-pip.py --no-index --find-links=/local/copies

Install to the user site [3]:

Install behind a proxy:

python get-pip.py --proxy="http://[user:passwd@]proxy.server:port"

Upgrading pip¶

On Linux or macOS:

On Windows [4]:

python -m pip install -U pip

Python and OS Compatibility¶

pip works with CPython versions 2.7, 3.3, 3.4, 3.5, 3.6 and also pypy.

This means pip works on the latest patch version of each of these minor
versions. Previous patch versions are supported on a best effort approach.

pip works on Unix/Linux, macOS, and Windows.


[1] “Secure” in this context means using a modern browser or a
tool like curl that verifies SSL certificates when downloading from
https URLs.
[2] Beginning with pip v1.5.1, get-pip.py stopped requiring setuptools to
be installed first.
[3] The pip developers are considering making --user the default for all
installs, including get-pip.py installs of pip, but at this time,
--user installs for pip itself, should not be considered to be fully
tested or endorsed. For discussion, see Issue 1668.
[4] https://github.com/pypa/pip/issues/1299

Что представляют собой пакеты и модули, откуда их брать и что с ними делать.

https://gbcdn.mrgcdn.ru/uploads/post/1340/og_cover_image/a9b1c9e84cf2c603aa80f227403c4177

Прежде чем что-то устанавливать, давайте разберёмся, что такое пакет, чем он отличается от модуля, и как с ним работать. У слова «пакет» применительно к Python два значения.

C одной стороны, пакеты Python  —  это Py-приложения, дополнения или утилиты, которые можно установить из внешнего репозитория: Github, Bitbucket, Google Code или официального Python Package Index. На сервере пакеты хранятся в .zip и .tar архивах, либо в дополнительной упаковке  —  «яйцах» (.egg,  старый формат)  или «колесах» (.whl). В составе пакета, как правило, есть сценарий установки setup.py, который хранит сведения о зависимостях —  других пакетах и модулях, без которых пакет работать не будет.

С другой стороны, если речь об архитектуре Python-приложения, пакет —  это каталог, внутри которого файл  __init__.py и, опционально, другие каталоги и файлы .py. Так большую Python-программу разбивают на пакеты и модули. Модуль —  файл с исходным кодом, который можно использовать в других приложениях: как «заготовку» для будущих проектов или как часть библиотеки/фреймворка. Но к теме статьи это прямого отношения не имеет, поэтому дальше мы будем говорить только о пакетах из репозиториев.

Чтобы за секунды устанавливать пакеты со всеми зависимостями, используют менеджер пакетов pip или модуль easy_install. В большинстве случаев рекомендуется использовать pip. И только если у вас есть инфраструктура на пакетах .egg, которые pip не открывает, нужен easy_install.

Установка PIP для Python 3 и 2

Если вы используете виртуальные окружения на базе venv или virtualenv, pip уже установлен. Начиная с Python 3.4 (для Python 2  —  с версии 2.7.9)  pip поставляется вместе с интерпретатором. Для более ранних версий устанавливать менеджер пакетов  нужно вручную. Вариантов два:

  1. C помощью скрипта get_pip.py  —  быстро.

  2. Через setuptools —  кроме pip сможем использовать easy_install.

Вариант 1. Скачиваем скрипт get_pip.py и запускаем в консоли. Для этого открываем терминал через Win+R>»cmd»>OK и пишем:

python get_pip.py

Остальное установщик сделает сам: если нужно, попутно установит wheel (для распаковки .whl-колес) и setuptools. Чтобы запретить инсталляцию дополнительных инструментов, можно добавить в строку ключи —no-setuptools и/или —no-wheels.

Если возникает ошибка, путь к Python не прописан в переменной среды $PATH. Нужно либо найти эту переменную в системном реестре и задать её значение, либо каждый раз указывать полный путь до python.exe, а за ним уже имя исполняемого Py-файла:

C:/python32/python.exe get_pip.py

Полный путь полезен и в том случае, если у вас на компьютере несколько версий Python и вы ставите пакет для одной из них.

Вариант 2. Скачиваем архив с setuptools из PYPI и распаковываем в отдельный каталог. В терминале переходим в директорию setuptools c файлом setup.py и пишем:

python setup.py install

Обновить pip для Python в Windows можно так:
python pip install -U pip

Если это не работает, нужно добавить путь к папке с pip в $PATH.

Установка пакета в pip

Пора запустить pip в Python и начать устанавливать пакеты короткой командой из консоли:

pip install имя_пакета

При установке в Windows, перед pip  нужно добавить «python -m».

Обновить пакет не сложнее:

pip install имя_пакета -U

Если у вас последняя версия пакета, но вы хотите принудительно переустановить его:

pip install --force-reinstall

Посмотреть список установленных пакетов Python можно с помощью команды:

pip list

Найти конкретный пакет по имени можно командой «pip search». О других командах можно прочесть в справке, которая выдается по команде «pip help».

Удаление пакета Python

Когда пакет больше не нужен, пишем:

pip uninstall имя_пакета

Как установить пакеты в Python без pip

Формат .egg сейчас используют не часто, поэтому pip его не поддерживает. Модуль easy_install умеет устанавливать как .egg, так и обычные пакеты, но есть у него важные минусы:

  • он не удаляет пакеты,

  • он может пытаться установить недозагруженный пакет.

Использовать easy_install можно сразу после установки setuptools. Хранится модуль в папке Scripts вашего интерпретатора. Если у вас в $PATH верно прописан путь, ставить пакеты из PYPI можно короткой командой:

easy_install имя_пакета

Для обновления после install и перед именем пакета нужно ставить ключ -U. Откатиться до нужной версии можно так:

easy_install имя_пакета=0.2.3

Если нужно скачать пакет из альтернативного источника, вы можете задать URL или локальный адрес на компьютере:

easy_install http://адрес_репозитория.ру/директория/пакет-1.1.2.zip

Чтобы узнать об опциях easy_install, запустим его с ключом -h:

easy_install -h   

Список пакетов, установленных через easy_install, хранится в файле easy-install.pth в директории /libs/site-packages/ вашего Python.

К счастью, удалять установленные через easy_install пакеты можно с помощью pip. Если же его нет, потребуется удалить пакет вручную и стереть сведения о нем из easy-install.pth.

Теперь вы умеете ставить и удалять пакеты для вашей версии Python.

Кстати, для тех, кто изучает Python, мы подготовили список полезных и практичных советов.

Содержание:развернуть

  • 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.x
  • python3 --version — для Python 3.x
  • python3.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

  1. Скачайте файл get-pip.py и сохраните у себя на компьютере.
  2. Откройте командную строку и перейдите в папку, в которой сохранен get-pip.py.
  3. В командной строке выполните команду: python get-pip.py или python3 get-pip.py.
  4. 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. Как правило, этого достаточно для работы с большей частью проектов.

Понравилась статья? Поделить с друзьями:
  • Как установить numlock по умолчанию windows 10
  • Как установить opera для всех пользователей windows 10
  • Как установить q4os рядом с windows
  • Как установить pip в pycharm windows
  • Как установить numba python на windows