在 CentOS 系统中设置 Python 的优先级,通常是指在多个 Python 版本之间指定默认使用的版本。下面按常见场景给你说明(以 CentOS 7 / 8 / Stream 为例)。
python --version
python3 --version
alternatives 设置 Python 优先级(推荐)alternatives 是 CentOS/RHEL 官方管理多版本命令的方式。
alternatives --display python
如果没有,需要先注册。
假设系统中有:
/usr/bin/python2.7/usr/bin/python3.8执行:
sudo alternatives --install /usr/bin/python python /usr/bin/python2.7 1
sudo alternatives --install /usr/bin/python python /usr/bin/python3.8 2
数字表示优先级(越大优先级越高)
sudo alternatives --config python
输出示例:
There are 2 programs that provide 'python'.
Selection Command
-----------------------------------------------
*+ 1 /usr/bin/python2.7
2 /usr/bin/python3.8
Enter to keep current selection[+], or type selection number:
输入数字即可切换。
python --version
python3 的优先级(不影响系统 python)⚠️ 强烈建议不要修改系统 /usr/bin/python 指向(尤其是 CentOS 8 以前),否则可能影响 yum。
sudo alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 1
sudo alternatives --install /usr/bin/python3 python3 /usr/bin/python3.9 2
切换:
sudo alternatives --config python3
PATH 临时设置优先级(不推荐长期使用)export PATH=/usr/local/python3.9/bin:$PATH
只对当前 shell 有效。
update-alternatives(Debian 系,CentOS 少用)CentOS 通常使用 alternatives,而不是 update-alternatives。
| 场景 | 建议 |
|---|---|
| 系统 Python | 不动 |
| 开发环境 | 使用 python3.x |
| 多版本管理 | 使用 alternatives |
| 项目隔离 | 使用 virtualenv / venv |
| 最新 Python | 使用 pyenv |
yum 依赖 Python 2,不要删除或修改 /usr/bin/pythondnf 使用 Python 3,相对安全,但仍建议只改 python3如果你愿意,可以告诉我:
我可以给你精确命令。