I'm trying to fix up one of my virtualenvs - I'd like to reset all of the installed libraries back to the ones that match production.
Is there a quick and easy way to do this with pip?
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.
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.
If you want to force pip to clear out its download cache and use the specific version you can do by using --no-cache-dir command. If you are using an older version of pip than upgrade it with pip install -U pip. This will help you clear pip cache.
I've found this snippet as an alternative solution. It's a more graceful removal of libraries than remaking the virtualenv:
pip freeze | xargs pip uninstall -y
In case you have packages installed via VCS, you need to exclude those lines and remove the packages manually (elevated from the comments below):
pip freeze | grep -v "^-e" | xargs pip uninstall -y
This will work for all Mac, Windows, and Linux systems. To get the list of all pip packages in the requirements.txt file (Note: This will overwrite requirements.txt if exist else will create the new one, also if you don't want to replace old requirements.txt then give different file name in the all following command in place requirements.txt).
pip freeze > requirements.txt
Now to remove one by one
pip uninstall -r requirements.txt
If we want to remove all at once then
pip uninstall -r requirements.txt -y
If you're working on an existing project that has a requirements.txt
file and your environment has diverged, simply replace requirements.txt
from the above examples with toberemoved.txt
. Then, once you have gone through the steps above, you can use the requirements.txt
to update your now clean environment.
And For single command without creating any file (As @joeb suggested).
pip uninstall -y -r <(pip freeze)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With