How to reinstall pip

How to reinstall pip

Installing and Updating Pip

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

mikemu1 on May 8, 2020

Why is sudo required on MacOS?

anas715272 on June 9, 2020

I am using my office laptop and while I update pip I get the following error on the command line

Jiri Jahn on June 13, 2020

Hi, I am currently on Ubuntu 20.04, and it seems that Python2 is not a standard part of the system equipment. However, to install pip I had to use sudo apt-get install python3-pip (the native linux python in this case being python 3.8.2)

larrykone on July 1, 2020

where do you discuss adding a directory to PATH to os x? Can one use TextMate or TextEdit?

WARNING: The scripts pip, pip2 and pip2.7 are installed in ‘/Users/ /Library/Python/2.7/bin’ which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use –no-warn-script-location.

Eelco on Nov. 10, 2020

Error messages about testresources

mhdhabboub on Jan. 21, 2022

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

Geir Arne Hjelle RP Team on Jan. 21, 2022

@mhdhabboub Yes, that’s a great habit. Here’s an article that goes into more detail about why: snarky.ca/why-you-should-use-python-m-pip/

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

Geir Arne Hjelle RP Team on Jan. 21, 2022

mhdhabboub on Jan. 21, 2022

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

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

Что такое Pip в Python?

Python PIP – это менеджер пакетов Python, который в основном помогает пользователям устанавливать, просматривать и использовать различные пакеты или модули. Чтобы работать с PIP, сначала нам нужно загрузить и настроить его в нашей системе.

How to reinstall pip. Смотреть фото How to reinstall pip. Смотреть картинку How to reinstall pip. Картинка про How to reinstall pip. Фото How to reinstall pip
Убедитесь, что Python уже установлен в вашей системе. Для этого на Windows откройте командную строку с помощью комбинации Win+X. На Mac Command+пробел, а на Linux – это Ctrl+Alt+T. Вводите команду:

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

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

Давайте посмотрим, как установить pip в Windows, Linux и Mac OS. PIP поставляется в комплекте с установщиками Python, т.е. версиями 2.7.9+ или 3.4+. Вам нужно будет явно установить его, если вы используете старую версию или хотите ее обновить.

Чтобы убедиться, что PIP установлен и работает корректно введите:

Еще один вариант вызова pip:

Но если же pip не установлен, то переходим далее.

1 Установка PIP в Windows

Чтобы начать использовать PIP в Windows, нам необходимо загрузить установочный файл PIP по этой ссылке: https://bootstrap.pypa.io/get-pip.py

Скопируйте содержимое из указанного выше URL-адреса и сохраните его с именем get-pip.py, после чего вам нужно открыть командную строку и перейти в каталог, где сохранен файл get-pip.py, и запустить файл.

Чтобы проверить, успешно ли установлен PIP в вашей системе, выполните следующую команду в CMD.

Вывод: на вашем терминале должен появиться следующий набор информации.

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

2 Установка PIP в Ubuntu

3 Установка PIP в Mac OS

Мы также можем использовать easy_install для установки PIP. Фактически, оба они являются менеджерами пакетов, а PIP заменил утилиту easy_install.

Официальная инструкция на английском языке тут https://pip.pypa.io/en/latest/installing.html

Обновление

Для обновления PIP достаточно

Скачивание и установка библиотек для Python через PIP

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

How to reinstall pip. Смотреть фото How to reinstall pip. Смотреть картинку How to reinstall pip. Картинка про How to reinstall pip. Фото How to reinstall pip
pip check — проверка зависимостей установленных пакетов на совместимость между собой.

$ pip check
No broken requirements found.

Установка определённой версии вместо новейшей версии пакета:

pip install package-name==1.0.0
Обновление устаревших пакетов:

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

Если вы увидите, например, на Github файл с именем requirements.txt, то знайте, что в этом файле указываются какие пакеты нужны для запуска данного проекта.

Сам файл requirements.txt создается командой:

pip freeze > requirements.txt
В итоге в нем отображаются следующие строчки:

beautifulsoup4==4.8.2
lxml==4.4.2
soupsieve==1.9.5

После этого скрипт и файл requirements.txt нужно поместить в систему для контроля версий.

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

Список пакетов

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

Команда list отображает установленные пакеты вместе с их версиями.

How to reinstall pip. Смотреть фото How to reinstall pip. Смотреть картинку How to reinstall pip. Картинка про How to reinstall pip. Фото How to reinstall pip
Список всех устаревших пакетов:

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

Если вы хотите удалить какой-либо пакет, следующая команда может помочь вам в этом.

Далее вам будет предложено согласие, действительно ли вы хотите удалить выбранный пакет. Введите «y», чтобы продолжить.

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

Команды PIP

PIP содержит множество команд для анализа и работы с модулями и пакетами Python.

Следующая команда может использоваться для получения информации о командах, поддерживаемых самим PIP.

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

Поиск пакетов

Иногда мы можем не знать точное имя пакета, и у PIP есть решение для этого. Мы можем легко найти пакет в репозитории, используя следующую команду.

Пример поиска пакетов:

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

Информация об установленном пакете

Если вы хотите получить информацию об установленном пакете или модуле, такую как расположение хранилища и последнюю версию, PIP может помочь нам с этим, используя следующую команду.

How to reinstall pip. Смотреть фото How to reinstall pip. Смотреть картинку How to reinstall pip. Картинка про How to reinstall pip. Фото How to reinstall pip
-f, —files — добавляет к основной информации полный список установленных файлов указанного пакета.

note.nkmk.me

pip is the package installer for Python. It is used to install, update, and uninstall various Python packages (libraries).

This article describes the following contents.

Install pip

If you install Python with the standard python.org installer, pip is installed at the same time.

Usually, pip is automatically installed if you are:

But if you don’t have pip installed, it is easier to set up a new Python environment with the python.org installer unless you have a strong reason to use old system.

On a Mac, Python 2.7 is installed by default, but pip is not included. If you install Python with Homebrew, the pip is installed at the same time.

In Anaconda, conda is used for package management instead of pip.

pip and pip2, pip3

If you have an environment where Python2 and Python3 coexist, you may be able to use the pip2 and pip3 commands in addition to the pip command.

pip2 is the command used to manage packages used by Python2, and pip3 is the command used to manage packages used by Python3. pip is assigned to either Python2 or Python3.

For example, note that if pip is for Python2, packages installed with pip will not work with Python3.

You can use the pip show command described next to check where each package has been installed.

Details of installed package: pip show

Use pip show to check the details of installed package.

For example, the pip itself is one of the packages, so you can see the details as follows. The license and dependencies are displayed.

Location is the path where the package is actually installed.

Note that this is just the result of the example environment, and depending on the environment, pip may be a command for Python3.

It is also possible to change the output format to output only up-to-date packages, outdated packages, packages that are not dependencies of other packages. See the following article for details.

Install a package: pip install

Use pip install to install a package.

If a package is registered in the PyPI (the Python Package Index), you can specify its name and install the latest version.

Multiple packages can be installed at the same time.

Install from local or GitHub

The packages registered in PyPI can be installed by name only, as described above.

If the latest or bug-fixed version is not yet registered in PyPI, you can install it from your local directory or GitHub repository.

You can also install it from the Git repository.

Install from GitHub:

You can specify a branch or tag by adding @
at the end.

For example, the version with the v2.15.0 tag of Requests can be installed as follows.

On GitHub, you can download each version of the repository as a zip file from the release page, so you can specify the zip URL directly. In this case, you do not need to have git installed on your system.

Update pip itself

The pip itself is also managed by pip.

If pip is not the latest version, the following message will be displayed when running the pip command.

As the message says, you can update the pip itself with the following command.

Uninstall a package: pip uninstall

Use pip uninstall to uninstall installed packages.

Multiple packages can be uninstalled at the same time.

By default, you are asked before files are actually deleted, as follows.

Type y to uninstall.

Check for dependencies: pip check

You can use pip check to verify that installed packages have compatible dependencies.

If everything is fine:

If a dependent package is not installed, or if it is installed but the version is not correct:

How to upgrade pip3?

I want to use python3.5 for development, but many times when I install the module for python 3.5, it always fails. The terminal tells me that a higher version is available, but it doesn’t work when I upgrade it. How to reinstall pip. Смотреть фото How to reinstall pip. Смотреть картинку How to reinstall pip. Картинка про How to reinstall pip. Фото How to reinstall pip

12 Answers 12

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

It might be a good idea to take some time and read about virtual environments in Python. It isn’t a best practice to install all of your packages to the base python installation. This would be a good start: http://docs.python-guide.org/en/latest/dev/virtualenvs/

To upgrade your pip3, try running:

Your pip may move from /bin to /usr/local/bin

To upgrade pip as well, you can follow it by:

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

Try this command:

First decide which pip you want to upgrade, i.e. just pip or pip3. Mostly it’ll be pip3 because pip is used by the system, so I won’t recommend upgrading pip.

The difference between pip and pip3 is that

NOTE: I’m referring to PIP that is at the BEGINNING of the command line.

pip is used by python version 2, i.e. python2

pip3 is used by python version 3, i.e. python3

For upgrading pip3: # This will upgrade python3 pip.

For upgrading pip: # This will upgrade python2 pip.

This will upgrade your existing pip to the latest version.

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

The Problem

You use pip (the Python 2 one). Now you want to upgrade pip (the Python 3 one). After that, pip is the Python 3 one.

The solution

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

What worked for me was the following command:

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

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

In Ubuntu 18.04, below are the steps that I followed.

For some reason you will be getting an error, and that be fixed by making bash forget the wrongly referenced locations using the following command.

If you have 2 versions of Python (eg: 2.7.x and 3.6), you need do:

How to Install and Uninstall Python Packages Using Pip

A step-by-step introduction to basic Python package management skills with the “pip” command. Learn how to install and remove third-party modules from PyPI.

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

Python is approaching its third decade of good old age, and over the years many people have contributed to the creation of Python packages that perform specific functions and operations.

As of this writing, there are

112K packages listed on the PyPI website. PyPI is short for “Python Package Index”, a central repository for free third-party Python modules.

This large and convenient module ecosystem is what makes Python so great to work with:

You see, most Python programmers are really assemblers of Python packages, which take care of a big chunk of the programming load required by modern applications.

Chances are that there is more than one Python package ready to be unleashed and help you with your specific programming needs.

For instance, while reading dbader.org, you may notice that the pages on the site render emoji quite nicely. You may wonder…

I’d like to use emoji on my Python app!

Is there a Python package for that?

Here’s what we’ll cover in this tutorial:

Finding Python Packages

Let’s use the emoji use case as an example. We find emoji related Python packages by visiting the PyPI website and searching for emoji via the search box on the top right corner of the page.

As of this writing, PyPI lists 94 packages, of which a partial list is shown below.

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

Notice the “ Weight* ” header of the middle column. That’s a key piece of information. The weight value is basically a search scoring number, which the site calculates for each package to rank them and list them accordingly.

If we read the footnote it tells us that the number is calculated by “the occurrence of search term weighted by field (name, summary, keywords, description, author, maintainer).”

Does that mean that the top one is the best package?

Not necessarily. Although uncommon, a package maintainer may stuff emoji into every field to try to top rank the package, which could well happen.

Conversely, many developers don’t do their homework and don’t bother filling out all the fields for their packages, which results in those packages being ranked lower.

You still need to research the packages listed, including a consideration for what your specific end use may be. For instance, a key question could be:

Which environment do you want to implement emoji on? A terminal-based app, or perhaps a Django web app?

If you are trying to display emoji on a django web app, you may be better off with the 10th package down the list shown above (package django-emoji 2.2.0 ).

For our use case, let’s assume that we are interested in emoji for a terminal based Python app.

Let’s check out the first one on our list (package emoji 0.4.5 ) by clicking on it.

What to Look for in a Python Package

The following are characteristics of a good Python package:

On our emoji example, the documentation seems decent. At the top of the page, we get a graphical indication of the package at work (see snippet below), which shows emoji on a Python interpreter. Yay!

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

The documentation for our emoji package also tells us about installing it, how to contribute to its development, etc., and points us to a GitHub page for the package, which is a great source of useful information about it.

By visiting its GitHub page, we can glean from it that the package has been around for at least two years, was last maintained in the past couple of months, has been starred 300+ times, has been forked 58 times, and has 10 contributors.

It’s looking good! We have identified a good candidate to incorporate emoji-ing into our Python terminal app.

How do we go about installing it?

Installing Python Packages With Pip

At this time, I am assuming that you already have Python installed on your system. There is plenty of info out there as to how to accomplish that.

I get the following output:

Since Python 3.4, pip is bundled with the Python installation package. If for some reason it is not installed, go ahead and get it installed.

I highly recommend also that you use a virtual environment (and more specifically, virtualenvwrapper ), a set of extensions that…

…include wrappers for creating and deleting virtual environments and otherwise managing your development workflow, making it easier to work on more than one project at a time without introducing conflicts in their dependencies.

Below you’ll see how package dependencies can bring complexity into our already complex development environments, which is the reason why using virtual environments is a must for Python development.

Below is a partial list of the results on my terminal:

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

Let’s take a quick detour and focus on the freeze command next, which will be a key one in dealing with dependencies. Running pip freeze displays a list of all installed Python packages. If I run it with my freshly installed virtual environment active, I should get an empty list, which is the case:

Now we can get the Python interpreter going by typing python on our terminal. Once that’s done, let’s try to import the emoji module, upon which python will complain that there isn’t such a module installed, and rightfully so for we haven’t installed it, yet:

To finally install the package, we can go ahead and run pip install emoji on our terminal. I get the following output:

🚫 Getting a pip install “invalid syntax” error?

Please note that the pip install command needs to be run from the command-line inside your terminal program, and not inside the Python interpreter.

Pip is a program that installs modules, so you can use them from Python. Once you have installed the module, then you can open the Python shell and import the module.

A specific version of the package ( == ):

A version equal to or greater than a specific version ( >= ):

A version of the package in the specified range ( >=X.Y.T, ):

You may be wondering why you would want to install an older version of a Python package in the first place:

One good example of that is if you are following a tutorial which might have used the latest version of a package when it was written but which could be an older version by the time you are reading it. If you want to follow along, you would do well by installing the same version that the author used.

Another example is that if you start writing code for an app today, chances are that the packages that you use today will evolve, and new versions of it will be released in the future (while your app is “stuck” with the versions that you use today).

Programmers freeze requirements to keep track of the versions of the different packages that are installed on development and production environments. One of the objectives is to be able to replicate the environments as needed. Dan’s course on Python dependency management goes into more detail on that topic.

Let’s continue on and run pip freeze again after installing the emoji package. You should now see it included in the list of all installed Python modules:

As expected, pip freeze now lists the emoji package as an added dependency with a specific version number.

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

Success, at last! We just installed and then imported a third-party Python module. Great job 🙂

It’s typical for an application to have several interdependent packages. For instance, running pip freeze on the virtual environment that I use to develop tumblingprogrammer.com, will output the following list of modules:

That’s a total of 25 Python packages. And it’s a fairly simple application. Later on I’ll describe a way to visualize the interdependency between packages.

Capturing Installed Python Packages with Requirements Files

Developers get in the habit of freezing requirements every time that a package or a dependency gets installed on their projects. We do that by running the following pip command:

This dumps the output of pip freeze into a requirements.txt file on the working directory.

Let’s assume now that for some reason we need to install MarkupSafe version 0.11. Let’s assume also that we have gotten ahead, installed it, tested it, and that our app behaves as we expect it to.

I get the following output (if you are following along, yours might differ a little bit, for my computer had cached the files from a previous install):

I want to call your attention to the following lines, extracted from the above listing:

Take a close look…

You’ll see that pip doesn’t have a way of reconciling conflicting dependencies. Without even warning us, it went ahead and replaced version 0.11 with version 1.0 of our MarkupSafe package. And that could be trouble for our application.

At that point in time, we run our app tests (assuming that have them), and dig into our application to make sure that the changes between 0.11 and 1.0 of the MarkupSafe package don’t break it.

Now we’re going to add another package with dependencies to increase the complexity of our setup. We’ll install version 6.0 of a package called alembic by running:

I now call your attention to the following line from the above listing:

The listing above showing all the packages on our emoji application is not very helpful at the moment, for it doesn’t give us info on dependencies (it only lists packages in alphabetical order). Let’s fix that.

Visualizing Installed Packages

Once it’s done, let’s run pip freeze to see what we get:

We notice much more useful information here, including dependencies, and the minimum versions required for dependent packages to work properly.

Notice, once again, how MarkupSafe is listed twice, as both Jinja2 (and Flask ) and Mako (and alembic ) depend on it. That’s very useful information to troubleshoot things gone ugly.

Another benefit of using pipdeptree is that it warns us about conflicting dependencies, including circular ones (where packages depend on one another), but I have yet to see that in action. So far I couldn’t replicate the functionality on my system. You can find more info about the tool on its PyPI page.

Installing Python Packages From a requirements.txt File

If you have a requirements.txt file, you can install all the packages listed there by running the following command:

This is very handy when we want to replicate environments and have access to a requirements.txt that reflects the makeup of it.

Uninstalling Python Packages With Pip

In this section you’ll see how to uninstall individual Python packages from your system or active virtual environment, how you can remove multiple packages at once with a single command, and how you can remove all installed Python packages.

Uninstalling individual packages:

Let’s run pipdeptree to see what our setup looks like:

If you look carefully, you may notice that the alembic dependencies are still present, because pip uninstall does not get rid of them, by design.

We have to manually do that (there are other options, which we will cover below). Therefore, it is extremely important that we freeze our requirements and commit changes to our requirements.txt file every time that we install or uninstall packages so we know what our setup should look like if we need to roll back changes.

Uninstalling multiple Python packages at once:

You can also uninstall several packages at once, by using the following command-line syntax:

Another option is reading the list of packages to uninstall from a requirements file. Similar to its install counterpart, if you have a requirements.txt file, you can uninstall all the packages listed there like so:

Note that we could wipe out all the packages on our setup, which could actually be quite useful. Let’s take a look at an example.

The output below is a list of my git commits log ( gl is an alias on my bash profile for a prettified git log ):

Removing all installed Python packages:

Sometimes it can be useful to remove all installed packages in a virtual environment or on your system Python install. It can help you get back to a clean slate.

Running the following command will uninstall all Python packages in the currently active environment:

This command works by first listing all installed packages using the freeze command, and then feeding the list of packages into the pip uninstall command to remove them.

Installing and Uninstalling Python Packages with the “pip” Package Manager – Conclusion

Although we covered a lot of ground and shed light on key commands and major challenges that you may face when dealing with installing and uninstalling Python packages and their dependencies.

In summary, the workflow for the installation of a Python package with pip is as follows:

There is a lot more to cover, especially when it comes to dependency management, which has long-term implications on how we setup and configure our Python projects.

Such a complexity is one of the factors that make necessary to implement different settings and configurations to account for the distinct needs of our development, staging, and production environments.

What The Virtualenv?!
How You Can Avoid Python Dependency Management Pitfalls

Free 5-day class—just enter your email address below:

This article was filed under: dependency-management, and python.

About the Author

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

Jose Pumar is the creator behind tumbling programmer, where he shares about his experiences as a hobbyist programmer, and as of late, a Pythonista.

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

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

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