How to install pip3

How to install pip3

pip install#

Usage#

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:

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

Resolve dependencies. What will be installed is determined here.

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

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

Argument Handling#

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

Project or archive URL.

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

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#

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#

Installation Order#

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:

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:

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

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:

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

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.

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.

SSL Certificate Verification

Hash checking mode

Local Project Installs

Build System Interface

Options#

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

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

Don’t install package dependencies.

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

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

Only use wheels compatible with

. Defaults to the platform of the running system. Use this option multiple times to specify multiple platforms supported by the target interpreter.

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

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

Install everything relative to this alternate root directory.

Installation prefix where lib, bin and other top-level folders are placed

Directory to check out editable projects into. The default in a virtualenv is “ /src”. The default for global installs is “ /src”.

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

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

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 the Requires-Python information.

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

Check the build dependencies when PEP517 is used.

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

Compile Python source files to bytecode

Do not compile Python source files to bytecode

Do not warn when installing scripts outside PATH

Do not warn about broken dependencies

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.

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 older binary packages over newer source packages.

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

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

Don’t clean up build directories.

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.

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#

Install SomePackage and its dependencies from PyPI using Requirement Specifiers

Установка PIP на Python 3. Базовые команды

How to install pip3. Смотреть фото How to install pip3. Смотреть картинку How to install pip3. Картинка про How to install pip3. Фото How to install pip3

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

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

PIP — что это?

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

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

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

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

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

How to install pip3. Смотреть фото How to install pip3. Смотреть картинку How to install pip3. Картинка про How to install pip3. Фото How to install pip3

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

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

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

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

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

How to install pip3. Смотреть фото How to install pip3. Смотреть картинку How to install pip3. Картинка про How to install pip3. Фото How to install pip3

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

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

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

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

Если разговор идет о текущих версиях 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 uninstall package-name

Пример

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

sudo pip3 install numpy

pip3 install numpy

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

How to install pip3. Смотреть фото How to install pip3. Смотреть картинку How to install pip3. Картинка про How to install pip3. Фото How to install pip3

Python wheels

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

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

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

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

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

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

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

How to install pip3

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:

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`

For more information and examples, see the :ref:`pip install` reference.

Basic Authentication Credentials

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:

«Requirements files» are files containing a list of items to be installed using :ref:`pip install` like so:

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:

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.

Use a constraints file like so:

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

If no satisfactory wheels are found, pip will default to finding source archives.

To install directly from a wheel archive:

To include optional dependencies provided in the provides_extras metadata in the wheel, you must add quotes around the install target name:

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:

And then to install those requirements just using your local directory of wheels (and not from PyPI):

pip is able to uninstall most packages like so:

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.

To list installed packages:

To list outdated packages, and show the latest version available:

To show details about an installed package:

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:

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.

pip comes with support for command line completion in bash, zsh and fish.

To setup for bash:

To setup for zsh:

To setup for fish:

To setup for powershell:

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:

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:

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:

Then, to install from local only, you’ll be using :ref:`—find-links ` and :ref:`—no-index ` like so:

«Only if needed» Recursive Upgrade

As an historic note, an earlier «fix» for getting the only-if-needed behaviour was:

A proposal for an upgrade-all command is being considered as a safer alternative to the behaviour of eager upgrading.

To install «SomePackage» into an environment with site.USER_BASE customized to ‘/myappenv’, do the following:

To make the rules clearer, here are some examples:

From within a real python, where SomePackage is not installed globally:

From within a real python, where SomePackage is installed globally, but is not the latest version:

From within a real python, where SomePackage is installed globally, and is the latest version:

Fixing conflicting dependencies

Using pip from your program

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:

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

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:

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.

The big change in this release is to the pip dependency resolver within pip.

The most significant changes to the resolver are:

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.

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

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.

Troubleshoot and try these workarounds if necessary.

Please report bugs through the resolver testing survey.

Setups to test with special attention

Examples to try

Specific things we’d love to get feedback on:

Please let us know through the resolver testing survey.

We plan for the resolver changeover to proceed as follows, using :ref:`Feature Flags` and following our :ref:`Release Cadence` :

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

How to install python3 version of package via pip on Ubuntu?

18 Answers 18

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

I came across this and fixed this without needing the likes of wget or virtualenvs (assuming Ubuntu 12.04):

, superuser permissions are required.

You may want to build a virtualenv of python3, then install packages of python3 after activating the virtualenv. So your system won’t be messed up 🙂

This could be something like:

Short Answer

Long Answer

The short answer applies only on newer systems. On some versions of Ubuntu the command is pip-3.2 :

If it doesn’t work, this method should work for any Linux distro and supported version:

Much python packages require also the dev package, so install it too:

Check also Tobu’s answer if you want an even more upgraded version of Python.

I want to add that using a virtual environment is usually the preferred way to develop a python application, so @felixyan answer is probably the best in an ideal world. But if you really want to install that package globally, or if need to test / use it frequently without activating a virtual environment, I suppose installing it as a global package is the way to go.

Using Python’s pip to Manage Your Projects’ Dependencies

Table of Contents

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: A Beginner’s Guide to Pip

In this tutorial, you’ll learn how to:

Free Bonus: 5 Thoughts On Python Mastery, a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level.

Getting Started With pip

So, what exactly does pip do? pip is a package manager for Python. That means it’s a tool that allows you to install and manage libraries and dependencies that aren’t distributed as part of the standard library. The name pip was introduced by Ian Bicking in 2008:

I’ve finished renaming pyinstall to its new name: pip. The name pip is [an] acronym and declaration: pip installs packages. (Source)

Finding pip on Your System

The Python 3 installer gives you the option to install pip when installing Python on your system. In fact, the option to install pip with Python is checked by default, so pip should be ready for you to use after installing Python.

You can verify that pip is available by looking for the pip3 executable on your system. Select your operating system below and use your platform-specific command accordingly:

The which command on Linux systems and macOS shows you where the pip3 binary file is located.

On Windows and Unix systems, pip3 may be found in more than one location. This can happen when you have multiple Python versions installed. If you can’t find pip in any location on your system, then you may consider reinstalling pip.

Instead of running your system pip directly, you can also run it as a Python module. In the next section, you’ll learn how.

Running pip as a Module

When you run your system pip directly, the command itself doesn’t reveal which Python version pip belongs to. This unfortunately means that you could use pip to install a package into the site-packages of an old Python version without noticing. To prevent this from happening, you can run pip as a Python module:

Sometimes you may want to be more explicit and limit packages to a specific project. In situations like this, you should run pip inside a virtual environment.

Using pip in a Python Virtual Environment

To avoid installing packages directly into your system Python installation, you can use a virtual environment. A virtual environment provides an isolated Python interpreter for your project. Any packages that you use inside this environment will be independent of your system interpreter. This means that you can keep your project’s dependencies separate from other projects and the system at large.

Using pip inside a virtual environment has three main advantages. You can:

Python 3 has the built-in venv module for creating virtual environments. This module helps you create virtual environments with an isolated Python installation. Once you’ve activated the virtual environment, then you can install packages into this environment. The packages that you install into one virtual environment are isolated from all other environments on your system.

You can follow these steps to create a virtual environment and verify that you’re using the pip module inside the newly created environment:

Here you create a virtual environment named venv by using Python’s built-in venv module. Then you activate it with the source command. The parentheses ( () ) surrounding your venv name indicate that you successfully activated the virtual environment.

Reinstalling pip When Errors Occur

When you run the pip command, you may get an error in some cases. Your specific error message will depend on your operating system:

Operating SystemError Message
Windows‘pip’ is not recognized as an internal or external command,
operable program or batch file.
Linuxbash: pip: command not found
macOSzsh: command not found: pip

Note: Before you start any troubleshooting when the pip command doesn’t work, you can try out using the pip3 command with the three ( 3 ) at the end.

Getting errors like the ones shown above can be frustrating because pip is vital for installing and managing external packages. Some common problems with pip are related to how this tool was installed on your system.

Although the error messages for various systems differ, they all point to the same problem: Your system can’t find pip in the locations listed in your PATH variable. On Windows, PATH is part of the system variables. On macOS and Linux, PATH is part of the environment variables. You can check the contents of your PATH variable with this command:

The output of this command will show a list of locations (directories) on your disk where the operating system looks for executable programs. Depending on your system, locations can be separated by a colon ( : ) or a semicolon ( ; ).

By default, the directory that contains the pip executable should be present in PATH after you install Python or create a virtual environment. However, missing pip is a common issue. Two supported methods can help you install pip again and add it to your PATH :

The ensurepip module has been part of the standard library since Python 3.4. It was added to provide a straightforward way for you to reinstall pip if, for example, you skipped it when installing Python or you uninstalled pip at some point. Select your operating system below and run ensurepip accordingly:

Another way to fix your pip installation is to use the get-pip.py script. The get-pip.py file contains a full copy of pip as an encoded ZIP file. You can download get-pip.py directly from the PyPA bootstrap page. Once you have the script on your machine, then you run the Python script like this:

If none of the methods above work, then it might be worth trying to download the latest Python version for your current platform. You can follow the Python 3 Installation & Setup Guide to make sure that pip is appropriately installed and works without errors.

Installing Packages With pip

Python is considered a batteries included language. This means that the Python standard library contains an extensive set of packages and modules to help developers with their coding projects.

At the same time, Python has an active community that contributes an even more extensive set of packages that can help you with your development needs. These packages are published to the Python Package Index, also known as PyPI (pronounced Pie Pea Eye).

PyPI hosts an extensive collection of packages, including development frameworks, tools, and libraries. Many of these packages provide friendly interfaces to the Python standard library’s functionality.

Using the Python Package Index (PyPI)

When you want to use the requests package in your project, you must first install it into your environment. If you don’t want to install it in your system Python site-packages, then you can create a virtual environment first, as shown above.

Once you’ve created the virtual environment and activated it, then your command-line prompt shows the name of the virtual environment inside the parentheses. Any pip commands that you perform from now on will happen inside your virtual environment.

To install packages, pip provides an install command. You can run it to install the requests package:

In this example, you run pip with the install command followed by the name of the package that you want to install. The pip command looks for the package in PyPI, resolves its dependencies, and installs everything in your current Python environment to ensure that requests will work.

The pip install

command always looks for the latest version of the package and installs it. It also searches for dependencies listed in the package metadata and installs them to ensure that the package has all the requirements that it needs.

It’s also possible to install multiple packages in a single command:

By chaining the packages rptree and codetiming in the pip install command, you install both packages at once. You can add as many packages as you want to the pip install command. In cases like this, a requirements.txt file can come in handy. Later in this tutorial, you’ll learn how to use a requirements.txt file to install many packages at once.

You can use the list command to display the packages installed in your environment, along with their version numbers:

The pip list command renders a table that shows all installed packages in your current environment. The output above shows the version of the packages using an x.y.z placeholder format. When you run the pip list command in your environment, pip displays the specific version number that you’ve installed for each package.

To get more information about a specific package, you can look at the package’s metadata by using the show command in pip :

Now that you’ve installed requests and its dependencies, you can import it just like any other regular package in your Python code. Start the interactive Python interpreter and import the requests package:

Using a Custom Package Index

By default, pip uses PyPI to look for packages. But pip also gives you the option to define a custom package index.

Using pip with a custom index can be helpful when the PyPI domain is blocked on your network or if you want to work with packages that aren’t publicly available. Sometimes system administrators also create their own internal package index to better control which package versions are available to pip users on the company’s network.

For example, to install the rptree tool from the TestPyPI package index, you can run the following command:

Installing Packages From Your GitHub Repositories

You’re not limited to packages hosted on PyPI or other package indexes. pip also provides the option to install packages from a GitHub repository. But even when a package is hosted on PyPI, like the Real Python directory tree generator, you can opt to install it from its Git repository:

With the git+https scheme, you can point to a Git repository that contains an installable package. You can verify that you installed the package correctly by running an interactive Python interpreter and importing rptree :

Note: If you’re using a version control system (VCS) other than Git, pip has you covered. To learn how to use pip with Mercurial, Subversion, or Bazaar, check out the VCS Support chapter of the pip documentation.

Installing packages from a Git repository can be helpful if the package isn’t hosted on PyPI but has a remote Git repository. The remote repository you point pip to can even be hosted on an internal Git server on your company’s intranet. This can be useful when you’re behind a firewall or have other restrictions for your Python projects.

Installing Packages in Editable Mode to Ease Development

When working on your own package, installing it in an editable mode can make sense. By doing this, you can work on the source code while still using your command line like you would in any other package. A typical workflow is to first clone the repository and then use pip to install it as an editable package in your environment:

With the commands above, you installed the rptree package as an editable module. Here’s a step-by-step breakdown of the actions you just performed:

In the next section, you’ll learn how requirements files can help with your pip workflows.

Using Requirements Files

The pip install command always installs the latest published version of a package, but sometimes your code requires a specific package version to work correctly.

You want to create a specification of the dependencies and versions that you used to develop and test your application so that there are no surprises when you use the application in production.

Pinning Requirements

When you share your Python project with other developers, you may want them to use the same versions of external packages that you’re using. Maybe a specific version of a package contains a new feature that you rely on, or the version of a package that you’re using is incompatible with former versions.

These external dependencies are also called requirements. You’ll often find Python projects that pin their requirements in a file called requirements.txt or similar. The requirements file format allows you to specify precisely which packages and versions should be installed.

Running pip help shows that there’s a freeze command that outputs the installed packages in requirements format. You can use this command, redirecting the output to a file to generate a requirements file:

This command creates a requirements.txt file in your working directory with the following content:

Remember that x.y.z displayed above is a placeholder format for the package versions. Your requirements.txt file will contain real version numbers.

In the command above, you tell pip to install the packages listed in requirements.txt into your current environment. The package versions will match the version constraints that the requirements.txt file contains. You can run pip list to display the packages you just installed, with their version numbers:

Now you’re ready to share your project! You can submit requirements.txt into a version control system like Git and use it to replicate the same environment on other machines. But wait, what happens if new updates are released for these packages?

Fine-Tuning Requirements

The problem with hardcoding your packages’ versions and dependencies is that packages are updated frequently with bug and security fixes. You probably want to leverage those updates as soon as they’re published.

The requirements file format allows you to specify dependency versions using comparison operators that give you some flexibility to ensure packages are updated while still defining the base version of a package.

Open requirements.txt in your favorite editor and turn the equality operators ( == ) into greater than or equal to operators ( >= ), like in the example below:

You can change the comparison operator to >= to tell pip to install an exact or greater version that has been published. When you set a new environment by using the requirements.txt file, pip looks for the latest version that satisfies the requirement and installs it.

If a new version is available for a listed package, then the package will be upgraded.

In an ideal world, new versions of packages would be backward compatible and would never introduce new bugs. Unfortunately, new versions can introduce changes that’ll break your application. To fine-tune your requirements, the requirements file syntax supports additional version specifiers.

Changing the version specifier for the requests package ensures that any version greater than or equal to 3.0 doesn’t get installed. The pip documentation provides extensive information about the requirements file format, and you can consult it to learn more.

Separating Production and Development Dependencies

Freezing Requirements for Production

You created the production and development requirement files and added them to source control. These files use flexible version specifiers to ensure that you leverage bug fixes published by your dependencies. You’ve also tested your application and are now ready to deploy it to production.

You know that all the tests pass and the application works with the dependencies that you used in your development process, so you probably want to ensure that you deploy identical versions of dependencies to production.

The current version specifiers don’t guarantee that the identical versions will be deployed to production, so you want to freeze the production requirements before releasing your project.

After you’ve finished development with your current requirements, a workflow to create a new release of your current project can look like this:

With a workflow like this, the requirements_lock.txt file will contain exact version specifiers and can be used to replicate your environment. You’ve ensured that when your users install the packages listed in requirements_lock.txt into their own environments, they’ll be using the versions that you intend them to use.

Freezing your requirements is an important step to ensure that your Python project works the same way for your users in their environments as it did in yours.

Uninstalling Packages With pip

Once in a while, you’ll have to uninstall a package. Either you found a better library to replace it, or it’s something that you don’t need. Uninstalling packages can be a bit tricky.

Before you uninstall a package, make sure to run the show command for that package:

You should run the show command against all of the requests dependencies to ensure that no other libraries also depend on them. Once you understand the dependency order of the packages that you want to uninstall, then you can remove them using the uninstall command:

In a single call, you can specify all the packages that you want to uninstall:

Remember to always check the dependencies of packages that you want to uninstall. You probably want to uninstall all dependencies, but uninstalling a package used by others will break your working environment. In consequence, your project may not work correctly anymore.

If you’re working in a virtual environment, it can be less work to just create a new virtual environment. Then you can install the packages that you need instead of trying to uninstall the packages that you don’t need. However, pip uninstall can be really helpful when you need to uninstall a package from your system Python installation. Using pip uninstall is a good way to declutter your system if you accidentally install a package system-wide.

Exploring Alternatives to pip

Here are some other package management tools that are available for Python:

ToolDescription
CondaConda is a package, dependency, and environment manager for many languages, including Python. It comes from Anaconda, which started as a data science package for Python. Consequently, it’s widely used for data science and machine learning applications. Conda operates its own index to host compatible packages.
PoetryPoetry will look very familiar to you if you’re coming from JavaScript and npm. Poetry goes beyond package management, helping you build distributions for your applications and libraries and deploying them to PyPI.
PipenvPipenv is another package management tool that merges virtual environment and package management in a single tool. Pipenv: A Guide to the New Python Packaging Tool is a great place to start learning about Pipenv and its approach to package management.

Only pip comes bundled in the standard Python installation. If you want to use any alternatives listed above, then you have to follow the installation guides in their documentation. With so many options, you’re sure to find the right tools for your programming journey!

Conclusion

Many Python projects use the pip package manager to manage their dependencies. It’s included with the Python installer, and it’s an essential tool for dependency management in Python.

In this tutorial, you learned how to:

In addition, you’ve learned about the importance of keeping dependencies up to date and alternatives to pip that can help you manage those dependencies.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: A Beginner’s Guide to Pip

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

How to install pip3. Смотреть фото How to install pip3. Смотреть картинку How to install pip3. Картинка про How to install pip3. Фото How to install pip3

About Philipp Acsany

How to install pip3. Смотреть фото How to install pip3. Смотреть картинку How to install pip3. Картинка про How to install pip3. Фото How to install pip3 How to install pip3. Смотреть фото How to install pip3. Смотреть картинку How to install pip3. Картинка про How to install pip3. Фото How to install pip3

Philipp is a Berlin-based software engineer with a graphic design background and a passion for full-stack web development.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

How to install pip3. Смотреть фото How to install pip3. Смотреть картинку How to install pip3. Картинка про How to install pip3. Фото How to install pip3

How to install pip3. Смотреть фото How to install pip3. Смотреть картинку How to install pip3. Картинка про How to install pip3. Фото How to install pip3

How to install pip3. Смотреть фото How to install pip3. Смотреть картинку How to install pip3. Картинка про How to install pip3. Фото How to install pip3

How to install pip3. Смотреть фото How to install pip3. Смотреть картинку How to install pip3. Картинка про How to install pip3. Фото How to install pip3

How to install pip3. Смотреть фото How to install pip3. Смотреть картинку How to install pip3. Картинка про How to install pip3. Фото How to install pip3

How to install pip3. Смотреть фото How to install pip3. Смотреть картинку How to install pip3. Картинка про How to install pip3. Фото How to install pip3

How to install pip3. Смотреть фото How to install pip3. Смотреть картинку How to install pip3. Картинка про How to install pip3. Фото How to install pip3

How to install pip3. Смотреть фото How to install pip3. Смотреть картинку How to install pip3. Картинка про How to install pip3. Фото How to install pip3

Master Real-World Python Skills With Unlimited Access to Real Python

How to install pip3. Смотреть фото How to install pip3. Смотреть картинку How to install pip3. Картинка про How to install pip3. Фото How to install pip3

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Master Real-World Python Skills
With Unlimited Access to Real Python

How to install pip3. Смотреть фото How to install pip3. Смотреть картинку How to install pip3. Картинка про How to install pip3. Фото How to install pip3

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal. Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *