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

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

  • автор:

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

How To Uninstall Python Packages

Uninstalling Python packages and their dependencies can be done using the pip package manager. The pip package manager is a built-in tool for Python that can be used to install, upgrade, and uninstall packages.

Following is a step-by-step explanation of how to uninstall a package in Python using pip:

  1. Open a terminal/command prompt
  2. Check if pip is installed
  3. List installed packages
  4. Uninstall the package
  5. Verify that the package is uninstalled

Open a terminal/command prompt

Open a terminal/command prompt on your system.

Check if pip is installed

Check if pip is installed on your system by running the following command:

If pip is installed, you will see its version number in the output. If not, you will see an error message.

List installed packages

List all the packages that are currently installed on your system using the following command:

Above command command will display a list of all the packages installed on your system along with their version numbers.

Uninstall the package

To uninstall a package, use the following command:

Replace package_name with the name of the package you want to uninstall.

If the package has any dependencies that are no longer required, pip will also prompt you to uninstall them. You can choose whether or not to uninstall them by typing y or n.

Verify that the package is uninstalled

After the package is uninstalled, verify that it is no longer installed on your system by running the pip list command again.

If the package is no longer listed, then it has been successfully uninstalled.

Now you have successfully uninstalled a package in Python using pip.

Uninstalling python packages and dependencies

Uninstalling Python packages and dependencies

If the package has dependencies that are no longer required, pip will prompt you to uninstall them as well. You can choose to uninstall the dependencies by typing y or to keep them by typing n.

Verify the package is uninstalled

To verify that the package has been successfully uninstalled, run the pip list command again:

If the package is no longer listed, then it has been successfully uninstalled.

Uninstall dependencies

If you have uninstalled a package and want to remove its dependencies, you can use the pip autoremove command:

Above command will remove any packages that are no longer needed by your system.

It’s important to note that, be careful when using the pip autoremove command as it may remove packages that are still being used by other packages. It’s always a good idea to verify which packages will be removed before running this command.

Now you have successfully uninstalled a Python package and its dependencies using pip.

Uninstall packages in a Python virtual environment

Uninstalling packages in a Python virtual environment is similar to uninstalling packages in a standard Python environment. However, it is important to activate the virtual environment before running the uninstallation command.

Following are the steps to uninstall packages in a Python virtual environment:

Activate the virtual environment

Navigate to the directory where the virtual environment is installed and activate it. The activation command depends on the operating system and the shell you are using.

On Windows using Command Prompt, you can activate the virtual environment by running the following command:

On macOS or Linux using bash shell, you can activate the virtual environment by running the following command:

Uninstall the package

Once the virtual environment is activated, you can use the pip uninstall command to uninstall the package. Replace package_name with the name of the package you want to uninstall:

Verify the package is uninstalled

To verify that the package has been successfully uninstalled, run the following command:

Above command will display a list of all installed packages in the virtual environment. If the package you just uninstalled is not listed, then it has been successfully uninstalled.

Deactivate the virtual environment

After you have uninstalled the package, you can deactivate the virtual environment by running the following command:

Above command will return your command prompt to the standard shell environment.

Now you have successfully uninstalled a package in a Python virtual environment.

Uninstall Python Package Dependencies With Pipenv

Pipenv is a tool for managing Python environments and packages. It provides a way to install packages in a virtual environment, along with their dependencies. To uninstall a package and its dependencies using Pipenv, follow these steps:

Activate the Pipenv environment

Open your command line interface and navigate to the directory where your Pipenv environment is located. Activate the environment by running the following command:

Above command will activate the virtual environment and set the environment variables needed to use Pipenv.

Uninstall the package and its dependencies

To uninstall a package and its dependencies, use the following command:

Replace package_name with the name of the package you want to uninstall.

For example, if you want to uninstall the numpy package and its dependencies, you can type:

Above command will remove the numpy package and its dependencies from your virtual environment.

Verify the package and its dependencies are uninstalled

To verify that the package and its dependencies have been successfully uninstalled, use the pipenv graph command to list all the packages installed in the virtual environment:

Above command will display a list of all the packages installed in the virtual environment, along with their dependencies. If the package and its dependencies are no longer listed, then they have been successfully uninstalled.

Deactivate the Pipenv environment

After you have uninstalled the package and its dependencies, you can deactivate the virtual environment by running the following command:

Above command will return your command prompt to the standard shell environment.

Now you have successfully uninstalled a package and its dependencies using Pipenv.

Uninstall A python Package Installed With Setuptools

Uninstalling a Python package installed with Setuptools is similar to uninstalling a package installed with pip.

Менеджер пакетов 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 . Но откуда известно, что они нужны?

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

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