在 Ubuntu 上切换 Python 版本有多种方式,取决于你是临时使用、系统级别切换还是虚拟环境隔离。下面按常见场景说明(以 Ubuntu 20.04 / 22.04 为例)。
一、查看已安装的 Python 版本
ls /usr/bin/python*
python3 --version
二、临时切换(不推荐长期使用)
直接在命令中指定版本:
python3.8
python3.10
三、使用 update-alternatives(推荐:系统级切换)
1️⃣ 安装多个 Python 版本
sudo apt update
sudo apt install python3.8 python3.10
2️⃣ 注册到 alternatives
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.8 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 2
3️⃣ 切换默认 python3 版本
sudo update-alternatives --config python3
输出示例:
There are 2 choices for the alternative python3:
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/python3.10 2 auto mode
1 /usr/bin/python3.8 1 manual mode
2 /usr/bin/python3.10 2 manual mode
Press <enter> to keep the current choice[*], or type selection number:
✅ 切换后验证:
python3 --version
四、只改 python 命令(可选)
sudo ln -sf /usr/bin/python3.10 /usr/bin/python
⚠ 不推荐
- Ubuntu 很多系统工具依赖
python指向固定版本 - 可能导致
apt/systemd出错
五、使用虚拟环境(✅ 最佳实践)
1️⃣ 创建指定 Python 版本的虚拟环境
python3.10 -m venv venv
2️⃣ 激活
source venv/bin/activate
3️⃣ 验证
python --version
✅ 优点:
- 不影响系统 Python
- 每个项目可独立使用不同版本
六、使用 pyenv(多版本管理神器 ✅)
1️⃣ 安装 pyenv
curl https://pyenv.run | bash
按提示把以下内容加入 ~/.bashrc:
export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init --path)"
eval "$(pyenv init -)"
然后:
source ~/.bashrc
2️⃣ 安装 Python
pyenv install 3.9.13
pyenv install 3.11.6
3️⃣ 切换版本
pyenv global 3.11.6 # 全局
pyenv local 3.9.13 # 当前目录
pyenv shell 3.9.13 # 当前 shell
七、Ubuntu 20.04 / 22.04 默认情况
| 系统 | 默认 Python |
|---|---|
| 20.04 | Python 3.8 |
| 22.04 | Python 3.10 |
⚠ 不要删除系统默认 Python!
八、推荐方案总结
| 场景 | 推荐方式 |
|---|---|
| 临时测试 | python3.x |
| 系统用户级 | update-alternatives |
| 项目开发 | ✅ 虚拟环境 |
| 多版本管理 | ✅ pyenv |
如果你愿意,可以告诉我:
- Ubuntu 版本
- 是否用于 生产 / 开发 / Docker
- 是否涉及
pip、apt、ansible、ROS等
我可以给你最安全的具体方案 ✅