在 CentOS 7 下安装 Python 3.8 并切换版本

在CentOS 7 下安装 Python 3.8,并使用 update-alternatives 指令切换版本

前提概述

重装CentOS 7后,通过python -V命令发现默认Python版本仍是2.7,在/usr/bin内有Python 3.6。
但我是海象运算符和fstring的忠实拥护者,因此想将默认版本升级到 Python3.8。

安装依赖

yum install libffi-devel zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gcc make -y

安装Python

使用wget https://www.python.org/ftp/python/3.8.12/Python-3.8.12.tgz下载 Python 3.8 的最后一个版本。

通过tar -zxvf Python-3.8.12.tgz解压,cd Python-3.8.12/进入文件夹。

最后,使用./configure && make && make install建立编译文件、编译、安装。

安装完成后,使用python3.8 -V验证安装。

配置 update-alternatives

查看Python3.8安装路径

[Rowan@Centos ~]# which python3.8
/usr/local/bin/python3.8

看到了路径,就可以使用 update-alternatives 添加三个版本的选项

update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1
update-alternatives --install /usr/bin/python python /usr/bin/python3.6 2
update-alternatives --install /usr/bin/python python /usr/local/bin/python3.8 3

使用update-alternatives --config python指令切换版本。

修复yum错误

yum 依赖 Python,而Python刚换完版本,能用就有鬼了。

因此需要修改两个文件,分别是/usr/bin/yum以及/usr/libexec/urlgrabber-ext-down

在第一行#!/usr/bin/python的后面指明版本:

#!/usr/bin/python2.7

至此,Python已经配置完成,后继可以使用update-alternatives --config python切换版本,update-alternatives --display python查看

ref:
update-alternatives︰管理指令和檔案的多個版本
Centos安装Python3.8

Edit with Markdown