在 Ubuntu 上切换 Python 版本,常见有几种场景。下面按最常用 → 进阶给你说明。
python --version
python3 --version
Ubuntu 不建议直接删除或修改 /usr/bin/python,而是用 update-alternatives。
ls /usr/bin/python*
常见如:
/usr/bin/python3.8
/usr/bin/python3.10
/usr/bin/python3.12
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.8 1
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.10 2
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.12 3
数字越大,优先级越高。
sudo update-alternatives --config python
输出示例:
There are 3 choices for the alternative python (providing /usr/bin/python).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/python3.12 3 auto mode
1 /usr/bin/python3.8 1 manual mode
2 /usr/bin/python3.10 2 manual mode
3 /usr/bin/python3.12 3 manual mode
Press <enter> to keep the current choice[*], or type selection number:
输入数字即可切换。
python --version
如果你不想影响系统 python,只切换 python3:
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.12 2
sudo update-alternatives --config python3
不修改系统 Python,而是为项目单独配置版本。
sudo apt install python3-venv
python3.10 -m venv venv
source venv/bin/activate
激活后:
python --version
就是该虚拟环境的 Python。
退出:
deactivate
适合开发环境,比系统方式灵活。
curl https://pyenv.run | bash
按提示把下面内容加到 ~/.bashrc 或 ~/.zshrc:
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init --path)"
eval "$(pyenv init -)"
重启终端。
pyenv install 3.10.12
pyenv install 3.12.1
pyenv global 3.10.12 # 全局
pyenv local 3.12.1 # 当前目录
pyenv shell 3.9.6 # 当前 shell
| 场景 | 推荐方式 |
|---|---|
| 系统级切换 | update-alternatives |
| 项目开发 | venv |
| 多版本管理 | pyenv |
| 新手 | 用 python3.x 明确指定 |
如果你愿意,可以告诉我:
我可以给你一条最合适的命令 ✅