如何卸载所有通过pip安装的包?清理Mac Python环境重建虚拟环境
Hey there, let's walk through how to clean up your global Python environment and get your Django/Flask projects back on track without accidentally deleting critical components. Since you're okay with rebuilding your virtual environments, this process will be straightforward and low-risk:
If your current Django/Flask venvs have custom dependencies or configurations you don't want to lose, export their requirements first to make rebuilding easier:
- Activate your Django venv:
source path/to/your/django-venv/bin/activate(Mac/Linux) - Export dependencies:
pip freeze > django-requirements.txt - Deactivate:
deactivate - Repeat for your Flask venv:
source path/to/your/flask-venv/bin/activate,pip freeze > flask-requirements.txt, thendeactivate
Instead of uninstalling packages one by one (which risks deleting critical tools), we'll bulk-uninstall all non-system-critical packages while keeping pip and setuptools intact:
- First, list all globally installed packages (excluding virtual environments):
pip3 list --user - Generate a list of packages to uninstall, excluding
pipandsetuptools:pip3 freeze --user | grep -vE "(pip|setuptools)" > to-uninstall.txt - Bulk-uninstall these packages (the
-yflag skips confirmation prompts):pip3 uninstall -y -r to-uninstall.txt - Verify the cleanup—your global environment should now only have
pipandsetuptools:pip3 list
With a clean global environment, you can create fresh, isolated venvs for your projects:
For Django:
- Create a new venv:
python3 -m venv django-fresh-venv - Activate it:
source django-fresh-venv/bin/activate - Install dependencies—either use your backup:
Or start fresh with your needed Django version:pip install -r django-requirements.txtpip install Django==3.0.8 - Test your model updates to confirm the issue is resolved:
python manage.py makemigrations && python manage.py migrate
For Flask:
- Create a new venv:
python3 -m venv flask-fresh-venv - Activate it:
source flask-fresh-venv/bin/activate - Install dependencies via your backup or fresh install:
pip install -r flask-requirements.txt # OR pip install Flask==1.1.2
To avoid this issue again, try these habits:
- Always check your terminal prompt for the
(venv-name)prefix before installing packages—this confirms you're in the right virtual environment - Name your venvs clearly (e.g.,
django-blog-venv,flask-api-venv) to avoid confusion - Consider using tools like
pipenvorpoetry—they automatically handle virtual environment creation and dependency isolation, reducing manual errors
内容的提问来源于stack exchange,提问作者Mark-Chi




