Explain Codes LogoExplain Codes Logo

How do I remove all packages installed by pip?

python
pip
virtual-environment
best-practices
Nikita BarsukovbyNikita Barsukov·Oct 2, 2024
TLDR

To uninstall all pip-installed packages, execute pip freeze | xargs pip uninstall -y. This command pip freeze generates a list of installed packages, and xargs feeds them into pip uninstall, eliminating each one without a confirmation prompt.

However, packages installed using version control systems like Github or Gitlab might slip through. These "editable" installs (using -e flag) can be excluded with grep -v "^-e":

pip freeze | grep -v "^-e" | xargs pip uninstall -y

And to focus on uninstalling only the package names without the attached URLs, use cut -d "@" -f 1:

pip freeze | grep -v "^-e" | cut -d "@" -f 1 | xargs pip uninstall -y

Clean up after the Party: Special Guests Included

After performing an uninstall operation, it's crucial to:

  • Check manually that the environment is left spick-and-span, especially regarding "github special guests" — the packages installed from version control systems.
  • For a speedy environment cleanup, try creating a bash alias like alias pipwipe='pip freeze | grep -v "^-e" | xargs pip uninstall -y'. Next time, instead of the entire command, just type pipwipe. Less typing equals to less potential RSI. Talk about killing two birds with one stone, eh?

My Environment, My Rules

Playing with virtual environments is similar to playing with "Lego". You can build, break and rebuild, and:

  • You must activate the correct virtual environment before summoning the Uninstaller Monster.
  • With virtualenv --clear MYENV, you can clean the environment. No need to repeal and replace!
  • For Pipenv users, imagine pipenv --rm as the magic broom sweeping away the dusty old packages.
  • For Poetry aficianados, poetry env remove python3.x is like your personal environmental cleanup crew.

Best Practices: Handle with Care

  • Storing the list of installed packages in a file (like using pip freeze > oldreqs.txt) before mass uninstallation can prove life-saving. You never know when you need to resurrect those zombie packages!
  • Ensure the safety of your system-required packages before invoking the dreaded rm -rf /*. Just kidding, the command is pip uninstall -r requirements.txt -y.
  • Consider pip-autoremove for an amazing diet program for your disk space. It removes the package and any of its unused dependencies!