Как удалить библиотеку в python через pip
Перейти к содержимому

Как удалить библиотеку в python через pip

  • автор:

How to delete an installed module in Python?

Python’s package manager is called PIP. In other words, it is a tool that enables us to install Python packages and dependencies (the software elements needed by your code to function without throwing any errors) that are not already available to us through the Python Standard Library.

A computer language’s tool that makes it simple to install any external dependencies is known as a package manager. Any package can be installed or uninstalled without issue.

Steps involved for uninstalling using pip

Following are the steps to uninstall a package or module using pip command −

Open the command prompt.

With the help of «PIP uninstall module_name” command, uninstall the module.

The flask package will be deleted.

In the Python 2.7 version, flask uninstall through pip.

This would be «pip3.6 uninstall —user flask» for Python 3.6.

Following a list of the files that need to be deleted, the command will request your approval. Enter the Enter key after typing «y» to confirm this action.

Note − Installed packages that are directly on the system cannot be removed.

Example

Following example shows how to uninstall python module using pip command −

Output

Following is an output of the above code −

Note − There are a few exceptions, though. Using pip, it is difficult to delete these packages:

Pure distutils packages installed with python setup.py install do not leave any metadata of the files they installed.

The script wrappers that Python setup.py develop install.

All files must be manually deleted, and any other activities performed during installation must be undone. If you are unsure about the complete list of files, you can reinstall it using the —record option and examine the results. To make a list of the installed file, you can use −

Now that you have a list of all the files in the files.txt, you may manually delete them.

Uninstalling a package using conda

The main tool for managing package installations is the conda command. It can −

  • Form new environments for conda.
  • The Anaconda package index and current Anaconda installation can be queried and searched.
  • Installing and updating packages in conda environments that already exist.

Steps involved for uninstalling using conda

Following are the steps to uninstall a package or module using conda command −

To view a list of all the Anaconda virtual environments, open the Anaconda Navigator window and select the Environments menu item from the window’s left side.

Select the Open Terminal menu option from the popup menu list after clicking the green triangle at the end of one Anaconda virtual environment.

It will enter your chosen anaconda virtual environment and start a dos or terminal window.

With the help of «conda uninstall module_name” command, uninstall the module.

To confirm the uninstall outcome, execute the conda list package-name command one more.

Example

Following example shows how to uninstall python module using conda command −

pip uninstall#

pip is able to uninstall most installed packages. Known exceptions are:

Pure distutils packages installed with python setup.py install , which leave behind no metadata to determine what files were installed.

Script wrappers installed by python setup.py develop .

Options#

-r , —requirement <file> #

Uninstall all the packages listed in the given requirements file. This option can be used multiple times.

Don’t ask for confirmation of uninstall deletions.

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

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

Smartiqa Article

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

Работа с этим хранилищем расширений осуществляется через команду pip . Имеется и другой установщик easy_install , но он применяется существенно реже. Таким образом, пакетный менеджер pip необходим для установки, обновления, удаления и управления модулями языка Python.

2. Подготовительные мероприятия

Как видно из ответа, на данном ПК используется python версии 3.8 и pip версии 20.2.3 .

В некоторых случаях (актуально для пользователей Linux или macOS ) требуется применять команду pip3 (если в результате выполнения pip определяет, что у вас установлен python версии 2 по умолчанию). Это связано с тем, что на *nix системах присутствуют сразу обе версии языка.

Также если на вашем компьютере имеется несколько версий языка Python (например, 3.6 , 3.8 , 3.9 ), то менеджер пакетов может применяться отдельно для каждой из них:

3. Установка и удаление пакетов

При разработке сложных проектов может понадобиться установка большого количества модулей. Постоянно их скачивать из репозитория PyPi трудоемко. Для этого разработан способ загрузки пакетов локально. Они могут находиться в архивах ( *.tar.gz ) или специальных файлах с расширением .whl . Это удобно и в том случае, если нет доступа в интернет у выбранной машины, и вы заранее создали пакет со всеми необходимыми библиотеками.

Для примера запакуем модуль numpy в «колесо» ( wheel ) и установим его оттуда.

Вначале мы создали специальный локальный пакет NumPy и поместили его в текущую папку (о чем свидетельствует точка). В директории создался файл numpy-1.19.2-cp38-cp38-win32.whl . На его основании даже без интернета мы легко сможем установить данную библиотеку. Команда «—no-index» говорит о том, чтобы мы не искали модуль в репозитории PyPi , а —find-links принудительно указывает место расположения пакета. Когда речь идет о сотне пакетов, это очень удобно. Правда для этого необходимо освоить еще один инструмент: набор зависимостей (о нем – следующий раздел).

Рассмотрим вопрос удаления модулей. Если требуется удалить один пакет, то делается это по аналогии с установкой:

Читайте также

4. Файлы требований для управления пакетами

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

How do I remove all packages installed by pip?

How do I uninstall all packages installed by pip from my currently activated virtual environment?

Mateen Ulhaq's user avatar

33 Answers 33

I’ve found this snippet as an alternative solution. It’s a more graceful removal of libraries than remaking the virtualenv:

In case you have packages installed via VCS, you need to exclude those lines and remove the packages manually (elevated from the comments below):

If you have packages installed directly from github/gitlab, those will have @ . Like:

You can add cut -d "@" -f1 to get just the package name that is required to uninstall it.

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

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