在 CentOS 上“切换 Python 版本”一般有几种场景,下面按常用程度给你说明,并附上安全做法(避免把系统 Python 搞坏)。
⚠️ 不要直接替换 /usr/bin/python
CentOS 7/8 的系统工具(yum、dnf)依赖系统自带 Python(如 2.7 或 3.6)。
强行改 python 指向会导致 yum 失效。
✅ 正确做法:用 alternatives 或虚拟环境,或显式使用 python3.x。
适合:多个 Python 已安装,想切换 python 命令
ls /usr/bin/python*
which python3
假设有 Python 3.8 和 3.9:
sudo alternatives --install /usr/bin/python python /usr/bin/python3.8 1
sudo alternatives --install /usr/bin/python python /usr/bin/python3.9 2
sudo alternatives --config python
按提示选择编号即可。
✅ 优点:干净、可回退
⚠️ 仍建议 不要动 python2(yum)
适合:开发、项目隔离
python3.9 -m venv venv
source venv/bin/activate
切换只需:
deactivate
source 其他环境/bin/activate
✅ 不影响系统
✅ 生产环境最推荐
适合:频繁切换 Python 版本
curl https://pyenv.run | bash
export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init -)"
pyenv install 3.10.12
pyenv global 3.10.12
✅ 不影响系统
✅ 可用户级切换
| 系统 | 默认 Python |
|---|---|
| CentOS 7 | python2.7 |
| CentOS 8 | python3.6 |
| CentOS Stream | python3.9+ |
查看:
cat /etc/centos-release
python --version
如果你告诉我:
我可以直接给你一步一步命令。