Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a pip requirements file to uninstall as well as install packages?

Tags:

python

pip

I have a pip requirements file that changes during development.

Can pip be made to uninstall packages that do not appear in the requirements file as well as installing those that do appear? Is there a standard method?

This would allow the pip requirements file to be the canonical list of packages - an 'if and only if' approach.

Update: I suggested it as a new feature at https://github.com/pypa/pip/issues/716

like image 732
wodow Avatar asked Nov 01 '12 12:11

wodow


People also ask

Can you use pip to uninstall a package?

Uninstalling/removing Python packages using Pip Open a terminal window. To uninstall, or remove, a package use the command '$PIP uninstall <package-name>'. This example will remove the flask package.

How do you remove all pip installed packages?

To remove all packages installed by pip with Python, we run pip uninstall . to run pip freeze to get the list of packages installed. And then we pipe that to xargs pip uninstall -y to remove all the packages listed by pip freeze with pip uninstall . We use the -y to remove everything without needing confirmation.


1 Answers

This should uninstall anything not in requirements.txt:

pip freeze | grep -v -f requirements.txt - | grep -v '^#' | xargs pip uninstall -y 

Although this won't work quite right with packages installed with -e, i.e. from a git repository or similar. To skip those, just filter out packages starting with the -e flag:

pip freeze | grep -v -f requirements.txt - | grep -v '^#' | grep -v '^-e ' | xargs pip uninstall -y 

Then, obviously:

pip install -r requirements.txt 

Update for 2016: You probably don't really want to actually use the above approach, though. Check out pip-tools and pip-sync which accomplish what you are probably looking to do in a much more robust way.

https://github.com/nvie/pip-tools

Update for May, 2016:

You can now also use pip uninstall -r requirements.txt, however this accomplishes basically the opposite - it uninstalls everything in requirements.txt

Update for May, 2019:

Check out pipenv or Poetry. A lot has happened in the world of package management that makes this sort of question a bit obsolete. I'm actually still quite happily using pip-tools, though.

like image 134
Stephen Fuhry Avatar answered Sep 28 '22 02:09

Stephen Fuhry