Ubuntu环境下已装Python3.6.5,如何移除Python2.7并恢复3.6默认?
Hey there! Let's walk through this carefully—Ubuntu 18.04 has some system components that still rely on Python 2.7, so we need to avoid breaking your OS while making Python 3.6 the default and cleaning up Python 2.7.
Step 1: Set Python 3.6 as the Default System Python
The safest way to set the default Python version is using update-alternatives (manual symlink edits can cause unexpected issues):
First, check what Python alternatives are already configured:
sudo update-alternatives --list pythonIf Python 3.6 isn't listed, add it with a high priority (higher numbers mean higher priority, ensuring it's chosen as default):
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.6 100Now set it as the default:
sudo update-alternatives --config pythonYou'll see a list of available versions—type the number corresponding to Python 3.6 and press Enter.
Verify the change worked:
python --versionYou should see output like
Python 3.6.5.
Step 2: Safely Remove Python 2.7
Before removing Python 2.7, check which system packages depend on it to avoid breaking core tools like apt:
dpkg -l | grep python2.7
Look for packages marked ii (installed). If you see core packages like python2.7-minimal linked to system utilities, don't force their removal.
Remove Non-Essential Python 2.7 Packages
If apt doesn't complain about critical dependencies, run these commands to remove Python 2.7 and clean up unused packages:
sudo apt remove --purge python2.7 python2.7-minimal sudo apt autoremove --purge
Critical Warning: If
aptthrows an error saying core packages (likeaptitself) depend on Python 2.7, stop immediately. Instead, only remove optional Python 2.7 packages (e.g.,python2.7-numpy) that were installed alongside your original numpy setup.
Clean Up Python 2.7 from Alternatives
If Python 2.7 was listed in the update-alternatives list earlier, remove it:
sudo update-alternatives --remove python /usr/bin/python2.7
Step 3: Verify Everything Works
- Double-check Python 3.6 is still default:
python --version python3 --version - Ensure core system tools still function properly by running:
If this runs without errors, you're good to go!sudo apt update
内容的提问来源于stack exchange,提问作者UTK007

