Как установить pip на windows через командную строку

Usage#

Unix/macOS

python -m pip install [options] <requirement specifier> [package-index-options] ...
python -m pip install [options] -r <requirements file> [package-index-options] ...
python -m pip install [options] [-e] <vcs project url> ...
python -m pip install [options] [-e] <local project path> ...
python -m pip install [options] <archive url/path> ...

Windows

py -m pip install [options] <requirement specifier> [package-index-options] ...
py -m pip install [options] -r <requirements file> [package-index-options] ...
py -m pip install [options] [-e] <vcs project url> ...
py -m pip install [options] [-e] <local project path> ...
py -m pip install [options] <archive url/path> ...

Description#

Install packages from:

  • PyPI (and other indexes) using requirement specifiers.

  • VCS project urls.

  • Local project directories.

  • Local or remote source archives.

pip also supports installing from “requirements files”, which provide
an easy way to specify a whole environment to be installed.

Overview#

pip install has several stages:

  1. Identify the base requirements. The user supplied arguments are processed
    here.

  2. Resolve dependencies. What will be installed is determined here.

  3. Build wheels. All the dependencies that can be are built into wheels.

  4. Install the packages (and uninstall anything being upgraded/replaced).

Note that pip install prefers to leave the installed version as-is
unless --upgrade is specified.

Argument Handling#

When looking at the items to be installed, pip checks what type of item
each is, in the following order:

  1. Project or archive URL.

  2. Local directory (which must contain a setup.py, or pip will report
    an error).

  3. Local file (a sdist or wheel format archive, following the naming
    conventions for those formats).

  4. A requirement, as specified in PEP 440.

Each item identified is added to the set of requirements to be satisfied by
the install.

Working Out the Name and Version#

For each candidate item, pip needs to know the project name and version. For
wheels (identified by the .whl file extension) this can be obtained from
the filename, as per the Wheel spec. For local directories, or explicitly
specified sdist files, the setup.py egg_info command is used to determine
the project metadata. For sdists located via an index, the filename is parsed
for the name and project version (this is in theory slightly less reliable
than using the egg_info command, but avoids downloading and processing
unnecessary numbers of files).

Any URL may use the #egg=name syntax (see VCS Support) to
explicitly state the project name.

Satisfying Requirements#

Once pip has the set of requirements to satisfy, it chooses which version of
each requirement to install using the simple rule that the latest version that
satisfies the given constraints will be installed (but see here
for an exception regarding pre-release versions). Where more than one source of
the chosen version is available, it is assumed that any source is acceptable
(as otherwise the versions would differ).

Obtaining information about what was installed#

The install command has a --report option that will generate a JSON report of what
pip has installed. In combination with the --dry-run and --ignore-installed it
can be used to resolve a set of requirements without actually installing them.

The report can be written to a file, or to standard output (using --report - in
combination with --quiet).

The format of the JSON report is described in Installation Report.

Installation Order#

Note

This section is only about installation order of runtime dependencies, and
does not apply to build dependencies (those are specified using PEP 518).

As of v6.1.0, pip installs dependencies before their dependents, i.e. in
“topological order.” This is the only commitment pip currently makes related
to order. While it may be coincidentally true that pip will install things in
the order of the install arguments or in the order of the items in a
requirements file, this is not a promise.

In the event of a dependency cycle (aka “circular dependency”), the current
implementation (which might possibly change later) has it such that the first
encountered member of the cycle is installed last.

For instance, if quux depends on foo which depends on bar which depends on baz,
which depends on foo:

Unix/macOS

$ python -m pip install quux
...
Installing collected packages baz, bar, foo, quux

$ python -m pip install bar
...
Installing collected packages foo, baz, bar

Windows

C:\> py -m pip install quux
...
Installing collected packages baz, bar, foo, quux

C:\> py -m pip install bar
...
Installing collected packages foo, baz, bar

Prior to v6.1.0, pip made no commitments about install order.

The decision to install topologically is based on the principle that
installations should proceed in a way that leaves the environment usable at each
step. This has two main practical benefits:

  1. Concurrent use of the environment during the install is more likely to work.

  2. A failed install is less likely to leave a broken environment. Although pip
    would like to support failure rollbacks eventually, in the mean time, this is
    an improvement.

Although the new install order is not intended to replace (and does not replace)
the use of setup_requires to declare build dependencies, it may help certain
projects install from sdist (that might previously fail) that fit the following
profile:

  1. They have build dependencies that are also declared as install dependencies
    using install_requires.

  2. python setup.py egg_info works without their build dependencies being
    installed.

  3. For whatever reason, they don’t or won’t declare their build dependencies using
    setup_requires.

Requirements File Format

This section has been moved to Requirements File Format.

Requirement Specifiers

This section has been moved to Requirement Specifiers.

Per-requirement Overrides

This is now covered in Requirements File Format.

Pre-release Versions#

Starting with v1.4, pip will only install stable versions as specified by
pre-releases by default. If a version cannot be parsed as a compliant PEP 440
version then it is assumed to be a pre-release.

If a Requirement specifier includes a pre-release or development version
(e.g. >=0.0.dev0) then pip will allow pre-release and development versions
for that requirement. This does not include the != flag.

The pip install command also supports a —pre flag
that enables installation of pre-releases and development releases.

VCS Support

This is now covered in VCS Support.

Finding Packages#

pip searches for packages on PyPI using the
HTTP simple interface,
which is documented here
and there.

pip offers a number of package index options for modifying how packages are
found.

pip looks for packages in a number of places: on PyPI (if not disabled via
--no-index), in the local filesystem, and in any additional repositories
specified via --find-links or --index-url. There is no ordering in
the locations that are searched. Rather they are all checked, and the “best”
match for the requirements (in terms of version number — see PEP 440 for
details) is selected.

See the pip install Examples.

SSL Certificate Verification

This is now covered in HTTPS Certificates.

Caching

This is now covered in Caching.

Wheel Cache

This is now covered in Caching.

Hash checking mode

This is now covered in Secure installs.

Local Project Installs

This is now covered in Local project installs.

Editable installs

This is now covered in Local project installs.

Build System Interface

This is now covered in Build System Interface.

Options#

-r, —requirement <file>#

Install from the given requirements file. This option can be used multiple times.

-c, —constraint <file>#

Constrain versions using the given constraints file. This option can be used multiple times.

—no-deps#

Don’t install package dependencies.

—pre#

Include pre-release and development versions. By default, pip only finds stable versions.

-e, —editable <path/url>#

Install a project in editable mode (i.e. setuptools “develop mode”) from a local project path or a VCS url.

—dry-run#

Don’t actually install anything, just print what would be. Can be used in combination with —ignore-installed to ‘resolve’ the requirements.

-t, —target <dir>#

Install packages into <dir>. By default this will not replace existing files/folders in <dir>. Use —upgrade to replace existing packages in <dir> with new versions.

—platform <platform>#

Only use wheels compatible with <platform>. Defaults to the platform of the running system. Use this option multiple times to specify multiple platforms supported by the target interpreter.

—python-version <python_version>#

The Python interpreter version to use for wheel and “Requires-Python”
compatibility checks. Defaults to a version derived from the running
interpreter. The version can be specified using up to three dot-separated
integers (e.g. “3” for 3.0.0, “3.7” for 3.7.0, or “3.7.3”). A major-minor
version can also be given as a string without dots (e.g. “37” for 3.7.0).

—implementation <implementation>#

Only use wheels compatible with Python implementation <implementation>, e.g. ‘pp’, ‘jy’, ‘cp’, or ‘ip’. If not specified, then the current interpreter implementation is used. Use ‘py’ to force implementation-agnostic wheels.

—abi <abi>#

Only use wheels compatible with Python abi <abi>, e.g. ‘pypy_41’. If not specified, then the current interpreter abi tag is used. Use this option multiple times to specify multiple abis supported by the target interpreter. Generally you will need to specify —implementation, —platform, and —python-version when using this option.

—user#

Install to the Python user install directory for your platform. Typically ~/.local/, or %APPDATA%Python on Windows. (See the Python documentation for site.USER_BASE for full details.)

—root <dir>#

Install everything relative to this alternate root directory.

—prefix <dir>#

Installation prefix where lib, bin and other top-level folders are placed. Note that the resulting installation may contain scripts and other resources which reference the Python interpreter of pip, and not that of --prefix. See also the --python option if the intention is to install packages into another (possibly pip-free) environment.

—src <dir>#

Directory to check out editable projects into. The default in a virtualenv is “<venv path>/src”. The default for global installs is “<current dir>/src”.

-U, —upgrade#

Upgrade all specified packages to the newest available version. The handling of dependencies depends on the upgrade-strategy used.

—upgrade-strategy <upgrade_strategy>#

Determines how dependency upgrading should be handled [default: only-if-needed]. “eager” — dependencies are upgraded regardless of whether the currently installed version satisfies the requirements of the upgraded package(s). “only-if-needed” — are upgraded only when they do not satisfy the requirements of the upgraded package(s).

—force-reinstall#

Reinstall all packages even if they are already up-to-date.

-I, —ignore-installed#

Ignore the installed packages, overwriting them. This can break your system if the existing package is of a different version or was installed with a different package manager!

—ignore-requires-python#

Ignore the Requires-Python information.

—no-build-isolation#

Disable isolation when building a modern source distribution. Build dependencies specified by PEP 518 must be already installed if this option is used.

—use-pep517#

Use PEP 517 for building source distributions (use —no-use-pep517 to force legacy behaviour).

—check-build-dependencies#

Check the build dependencies when PEP517 is used.

—break-system-packages#

Allow pip to modify an EXTERNALLY-MANAGED Python installation

-C, —config-settings <settings>#

Configuration settings to be passed to the PEP 517 build backend. Settings take the form KEY=VALUE. Use multiple —config-settings options to pass multiple keys to the backend.

—global-option <options>#

Extra global options to be supplied to the setup.py call before the install or bdist_wheel command.

—compile#

Compile Python source files to bytecode

—no-compile#

Do not compile Python source files to bytecode

—no-warn-script-location#

Do not warn when installing scripts outside PATH

—no-warn-conflicts#

Do not warn about broken dependencies

—no-binary <format_control>#

Do not use binary packages. Can be supplied multiple times, and each time adds to the existing value. Accepts either “:all:” to disable all binary packages, “:none:” to empty the set (notice the colons), or one or more package names with commas between them (no colons). Note that some packages are tricky to compile and may fail to install when this option is used on them.

—only-binary <format_control>#

Do not use source packages. Can be supplied multiple times, and each time adds to the existing value. Accepts either “:all:” to disable all source packages, “:none:” to empty the set, or one or more package names with commas between them. Packages without binary distributions will fail to install when this option is used on them.

—prefer-binary#

Prefer older binary packages over newer source packages.

—require-hashes#

Require a hash to check each requirement against, for repeatable installs. This option is implied when any package in a requirements file has a —hash option.

—progress-bar <progress_bar>#

Specify whether the progress bar should be used [on, off] (default: on)

—root-user-action <root_user_action>#

Action if pip is run as a root user. By default, a warning message is shown.

—report <file>#

Generate a JSON file describing what pip did to install the provided requirements. Can be used in combination with —dry-run and —ignore-installed to ‘resolve’ the requirements. When — is used as file name it writes to stdout. When writing to stdout, please combine with the —quiet option to avoid mixing pip logging output with JSON output.

—no-clean#

Don’t clean up build directories.

-i, —index-url <url>#

Base URL of the Python Package Index (default https://pypi.org/simple). This should point to a repository compliant with PEP 503 (the simple repository API) or a local directory laid out in the same format.

Extra URLs of package indexes to use in addition to —index-url. Should follow the same rules as —index-url.

—no-index#

Ignore package index (only looking at —find-links URLs instead).

-f, —find-links <url>#

If a URL or path to an html file, then parse for links to archives such as sdist (.tar.gz) or wheel (.whl) files. If a local path or file:// URL that’s a directory, then look for archives in the directory listing. Links to VCS project URLs are not supported.

Examples#

  1. Install SomePackage and its dependencies from PyPI using Requirement Specifiers

    Unix/macOS

    python -m pip install SomePackage            # latest version
    python -m pip install 'SomePackage==1.0.4'   # specific version
    python -m pip install 'SomePackage>=1.0.4'   # minimum version
    

    Windows

    py -m pip install SomePackage            # latest version
    py -m pip install "SomePackage==1.0.4"   # specific version
    py -m pip install "SomePackage>=1.0.4"   # minimum version
    
  2. Install a list of requirements specified in a file. See the Requirements files.

    Unix/macOS

    python -m pip install -r requirements.txt
    

    Windows

    py -m pip install -r requirements.txt
    
  3. Upgrade an already installed SomePackage to the latest from PyPI.

    Unix/macOS

    python -m pip install --upgrade SomePackage
    

    Windows

    py -m pip install --upgrade SomePackage
    

    Note

    This will guarantee an update to SomePackage as it is a direct
    requirement, and possibly upgrade dependencies if their installed
    versions do not meet the minimum requirements of SomePackage.
    Any non-requisite updates of its dependencies (indirect requirements)
    will be affected by the --upgrade-strategy command.

  4. Install a local project in “editable” mode. See the section on Editable Installs.

    Unix/macOS

    python -m pip install -e .                # project in current directory
    python -m pip install -e path/to/project  # project in another directory
    

    Windows

    py -m pip install -e .                 # project in current directory
    py -m pip install -e path/to/project   # project in another directory
    
  5. Install a project from VCS

    Unix/macOS

    python -m pip install 'SomeProject@git+https://git.repo/some_pkg.git@1.3.1'
    

    Windows

    py -m pip install "SomeProject@git+https://git.repo/some_pkg.git@1.3.1"
    
  6. Install a project from VCS in “editable” mode. See the sections on VCS Support and Editable Installs.

    Unix/macOS

    python -m pip install -e 'git+https://git.repo/some_pkg.git#egg=SomePackage'          # from git
    python -m pip install -e 'hg+https://hg.repo/some_pkg.git#egg=SomePackage'            # from mercurial
    python -m pip install -e 'svn+svn://svn.repo/some_pkg/trunk/#egg=SomePackage'         # from svn
    python -m pip install -e 'git+https://git.repo/some_pkg.git@feature#egg=SomePackage'  # from 'feature' branch
    python -m pip install -e 'git+https://git.repo/some_repo.git#egg=subdir&subdirectory=subdir_path' # install a python package from a repo subdirectory
    

    Windows

    py -m pip install -e "git+https://git.repo/some_pkg.git#egg=SomePackage"          # from git
    py -m pip install -e "hg+https://hg.repo/some_pkg.git#egg=SomePackage"            # from mercurial
    py -m pip install -e "svn+svn://svn.repo/some_pkg/trunk/#egg=SomePackage"         # from svn
    py -m pip install -e "git+https://git.repo/some_pkg.git@feature#egg=SomePackage"  # from 'feature' branch
    py -m pip install -e "git+https://git.repo/some_repo.git#egg=subdir&subdirectory=subdir_path" # install a python package from a repo subdirectory
    
  7. Install a package with extras.

    Unix/macOS

    python -m pip install 'SomePackage[PDF]'
    python -m pip install 'SomePackage[PDF] @ git+https://git.repo/SomePackage@main#subdirectory=subdir_path'
    python -m pip install '.[PDF]'  # project in current directory
    python -m pip install 'SomePackage[PDF]==3.0'
    python -m pip install 'SomePackage[PDF,EPUB]'  # multiple extras
    

    Windows

    py -m pip install "SomePackage[PDF]"
    py -m pip install "SomePackage[PDF] @ git+https://git.repo/SomePackage@main#subdirectory=subdir_path"
    py -m pip install ".[PDF]"  # project in current directory
    py -m pip install "SomePackage[PDF]==3.0"
    py -m pip install "SomePackage[PDF,EPUB]"  # multiple extras
    
  8. Install a particular source archive file.

    Unix/macOS

    python -m pip install './downloads/SomePackage-1.0.4.tar.gz'
    python -m pip install 'http://my.package.repo/SomePackage-1.0.4.zip'
    

    Windows

    py -m pip install "./downloads/SomePackage-1.0.4.tar.gz"
    py -m pip install "http://my.package.repo/SomePackage-1.0.4.zip"
    
  9. Install a particular source archive file following PEP 440 direct references.

    Unix/macOS

    python -m pip install 'SomeProject@http://my.package.repo/SomeProject-1.2.3-py33-none-any.whl'
    python -m pip install 'SomeProject @ http://my.package.repo/SomeProject-1.2.3-py33-none-any.whl'
    python -m pip install 'SomeProject@http://my.package.repo/1.2.3.tar.gz'
    

    Windows

    py -m pip install "SomeProject@http://my.package.repo/SomeProject-1.2.3-py33-none-any.whl"
    py -m pip install "SomeProject @ http://my.package.repo/SomeProject-1.2.3-py33-none-any.whl"
    py -m pip install "SomeProject@http://my.package.repo/1.2.3.tar.gz"
    
  10. Install from alternative package repositories.

    Install from a different index, and not PyPI

    Unix/macOS

    python -m pip install --index-url http://my.package.repo/simple/ SomePackage
    

    Windows

    py -m pip install --index-url http://my.package.repo/simple/ SomePackage
    

    Install from a local flat directory containing archives (and don’t scan indexes):

    Unix/macOS

    python -m pip install --no-index --find-links=file:///local/dir/ SomePackage
    python -m pip install --no-index --find-links=/local/dir/ SomePackage
    python -m pip install --no-index --find-links=relative/dir/ SomePackage
    

    Windows

    py -m pip install --no-index --find-links=file:///local/dir/ SomePackage
    py -m pip install --no-index --find-links=/local/dir/ SomePackage
    py -m pip install --no-index --find-links=relative/dir/ SomePackage
    

    Search an additional index during install, in addition to PyPI

    Warning

    Using this option to search for packages which are not in the main
    repository (such as private packages) is unsafe, per a security
    vulnerability called
    dependency confusion:
    an attacker can claim the package on the public repository in a way that
    will ensure it gets chosen over the private package.

    Unix/macOS

    python -m pip install --extra-index-url http://my.package.repo/simple SomePackage
    

    Windows

    py -m pip install --extra-index-url http://my.package.repo/simple SomePackage
    
  11. Find pre-release and development versions, in addition to stable versions. By default, pip only finds stable versions.

    Unix/macOS

    python -m pip install --pre SomePackage
    

    Windows

    py -m pip install --pre SomePackage
    
  12. Install packages from source.

    Do not use any binary packages

    Unix/macOS

    python -m pip install SomePackage1 SomePackage2 --no-binary :all:
    

    Windows

    py -m pip install SomePackage1 SomePackage2 --no-binary :all:
    

    Specify SomePackage1 to be installed from source:

    Unix/macOS

    python -m pip install SomePackage1 SomePackage2 --no-binary SomePackage1
    

    Windows

    py -m pip install SomePackage1 SomePackage2 --no-binary SomePackage1
    

Как любой серьёзный язык программирования, 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

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 …\Scripts\pip.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:\Python27\Scripts\pip.exe. Find pip.exe on your computer, then add its folder (for example, C:\Python27\Scripts) 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.

Pip — консольный менеджер пакетов для Python. Рассказываем как его установить, и какие возможности управления пакетами он предоставляет.

Pip — менеджер пакетов для Python, работа с ним осуществляется через командную строку. Pip не нужно устанавливать отдельно, если вы пользуетесь Python версии 2.7.9 и новее или версии 3.4 и новее. Если pip установлен, то можно ввести в командную строку:

Команды статье указаны для Windows, работа с pip в Linux может отличаться.

Вы получите справку по основным командам.

Установка pip для Python

Если pip не установлен, то нужно скачать скрипт. Выбирайте папку с номером вашей версии Python. После этого в командной строке перейдите в папку со скриптом и выполните команду:

Если pip установлен в папку ProgramFiles, то вам нужно запускать командную строку от администратора.

Если вы установили pip, но все равно получаете ошибку в консоли, нужно указать путь к файлу pip.exe в переменной Path. Для этого зайдите в свойства компьютера>Дополнительные параметры системы>Переменные среды. Здесь (в зависимости о версии Windows) либо добавьте путь к уже существующему через точку с запятой, либо просто нажмите создать и скопируйте путь в новое поле.

Если вам нужно обновить pip напишите в командной строке:

			python -m pip install --upgrade pip
		

Управление пакетами

Чтобы выполнить установку пакета с сайта pypi.org введите в консоли:

			python -m pip install ИмяПакета
		

Если вам нужно использовать несколько версий pip, то нужную можно указать так (начиная с версии pip 0.8):

			pip-0.8 install ИмяПакета
		

Таким же образом можно выбирать версию Python:

			python-3.6 -m pip install ИмяПакета
		

Pip версии 1.5 и выше следует указывать так:

Чтобы обновить пакет введите:

			python -m pip install --upgrade ИмяПакета
		

Для удаления пакета используйте команду uninstall:

			python -m pip uninstall ИмяПакета
		

Флаг -m используется для того чтобы запустить установленный модуль, как скрипт (если написать pip без -m вы можете получить ошибку).

Вывести список всех установленных пакетов в файл можно с помощью :

			pip freeze > requirements.txt // название файла может быть любым
		

При наличии такого файла, можно устанавливать пакеты группами:

			pip install -r requirements.txt// версии пакетов в файле указывать не обязательно
		

Необходимые пакеты можно найти не заходя на сайт pyPi.org (в данный момент недоступно):

			pip search строка для поиска
		

Чтобы узнать подробности об установленном пакете введите:

Проверить установлены ли все зависимости для ваших пакетов можно так:

Теперь, с этими знаниями, вы можете самостоятельно скачать пакет cowsay, зайти в python, и ввести этот текст:

			>>> import cowsay
>>> cowsay.cow('Я умею работать с pip! Му!')
		

Готово! У вас есть говорящая консольная корова:

В этой статье в очередной раз коснёмся темы установки PIP на Python. Вы узнаете, что делать, если PIP не установлена, как поставить эту систему, а также как выполняется инсталляция на Windows, Mac, Linux и Raspberry Pi. Дополнительно будут рассмотрены вопросы обновления и работы.

Python_Pro_970x90-20219-1c8674.png

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

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

Что же такое PIP?

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

Часто возникает вопрос, а не устанавливается ли PIP одновременно с Пайтоном? Да, если речь идёт о следующих версиях:
— Python версии 2.7.9 и выше;
— Python версии 3.4 и выше.

В вышеупомянутых случаях «пип» устанавливается по дефолту и вместе с Python. Но если же речь идёт о более старых версиях, PIP не установлена. Однако установить PIP совсем несложно. Но прежде чем это сделать, рекомендуется проверить свою версию Python, а также то, правильно ли он у вас инсталлирован.

Проверка версии Python

Для выполнения проверки Python следует открыть командную строку. Она вам понадобится и при последующих действиях. Следует привыкать работать с командной строкой, т. к. многие операции быстрее, удобнее и нагляднее выполнять именно через неё. Если же вы начинающий системный администратор, знание терминала — это пункт под номером 0 в списке необходимых скиллов.

Запускаем командную строку следующим образом:
1. На Windows. Используем комбинацию клавиш «Win+X».
2. На Mac. Нажимаем «Command+пробел».
3. На Линукс. Работает комбинация «Ctrl+Alt+T».

Когда терминал открыт, вводим следующую команду:


Если у вас Linux и Python 3.x, вводим несколько другую команду:


В итоге вы должны получить актуальную версию Питона, которая установлена на вашу операционную систему. Если же что-то не так, вы получите сообщение, что Пайтон не установлен (Python is not defined).

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

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

Всё, установка запустится (installs), и инсталляция модуля будет завершена в сжатые сроки. Способ простой и действенный.

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

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


Для установки более новых версий языка программирования Python вам пригодится Homebrew. С его помощью Пайтон устанавливается тоже очень просто (предполагается, что утилита командной строки Homebrew уже установлена):


По итогу получите последнюю версию Python, в которую, кстати говоря, система «пип» уже может входить. Но если же пакет будет недоступен, выполните перелинковку:

brew unlink python && brew link python

Python_Pro_970x90-20219-1c8674.png

Устанавливаем на Linux

Для дистрибутивов Linux желательно использовать системный менеджер пакетов и штатные репозитории. Команды могут различаться с учётом конкретного дистрибутива. Для примера возьмём популярный дистрибутив Ubuntu. Если у вас Python 3, в терминале выполняем:

sudo apt install python3-pip

А потом проверяем, что получилось:


Если же речь идёт о Пайтон 2, команды установки и проверки версии будут чуть другими:

sudo apt install python-pip

Как установить PIP на Raspberry Pi

Если вы являетесь пользователем Raspberry, эта часть статьи для вас. Если же вы даже не в курсе, что такое Raspberry, можете смело пропустить данный абзац.

Уже начиная с Rapsbian Jessie, система устанавливается по дефолту, то есть вопросов о том, что PIP не установлена, не возникает. Это ещё и причина обновить ОС до Rapsbian Jessie а не использовать Rapsbian Wheezy/Jessie Lite. Однако никто не мешает установить систему и на старую версию.

Для Python 2 это выглядит следующим образом:

sudo apt-get install python-pip

Для третьей версии изменения в команде крайне незначительны:

sudo apt-get install python3-pip

В процессе работы нужно будет применять pip и pip3 соответственно.

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

Для многих разработчиков очень важно иметь последнюю версию установщика программ. Это имеет особое значение, если мы говорим о сохранении приемлемого уровня безопасности, исправлении ошибок (багов) и т. д.

Обновить PIP не составляет труда:
1. Для Windows. Используем команду python -m pip install -U pip.
2. Для Mac, Линукс либо Raspberry Pi — pip install -U pip.

Устанавливаем Python-библиотеки посредством PIP

Когда установка (installing) завершена, «пип» установился и готов к работе. В результате мы можем приступать к установке пакетов с помощью PIP из PyPI. Делается это с помощью простейшего синтаксиса, содержащего минимум кода:


По умолчанию с помощью вышеприведённого синтаксиса будет установлена новейшая версия нужного пакета. Но иногда требуется конкретная версия, то есть более старая:

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

Также вы можете найти конкретный пакет:

pip search "ваш_запрос_поиска"

Или посмотреть детали уже установленного (installed):


Ещё пользователю доступен список всех пакетов, которые установлены:


А также список пакетов PIP, которые устарели:


Но это не беда, ведь можно выполнить обновление:

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

Однако учтите, что при обновлении старая версия будет удалена.
Ещё может возникнуть необходимость в полной переустановке пакета:

pip install имя_пакета --upgrade --force-reinstall

Совсем несложно и удалить пакет:


Это основы, которые должен знать каждый. Если же вас интересует Python-разработка на более продвинутом уровне, добро пожаловать на курсы в OTUS!

Python_Pro_970x550-20219-0846c7.png

Источники:
• https://pingvinus.ru/note/pip;
• https://pythonru.com/baza-znanij/ustanovka-pip-dlja-python-i-bazovye-komandy.

  • Как установить pip для python на windows
  • Как установить pip на windows cmd
  • Как установить picture manager на windows 10
  • Как установить pip в pycharm windows
  • Как установить physxloader dll для windows 10