编辑于2021-02-21
CentOS7.5默认只安装了Python2.7环境,python和python2命令均指向2.7版本
yum需要依赖Python2环境,自带Python和软链接均位于/usr/bin目录下
而现在主流开发环境早已不是Python2,因此我们需要考虑手动安装Python3,文中安装目录为/usr/local
-
安装用于编译Python3的依赖
[root@JetXi Python-3.9.2]# yum install zlib zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gcc make
-
在python.org找到download-sourcecode,下载Python3的xz包,也可直接使用wget下载
最新版本下载链接:https://www.python.org/ftp/python/3.9.2/Python-3.9.2.tar.xz
-
将xz包使用xftp上传到/usr/local目录,执行如下命令解压xz包
[root@JetXi local]# xz -d Python-3.9.2.tar.xz
[root@JetXi local]# tar xf Python-3.9.2.tar
-
进入解压得到的目录,依次执行如下命令编译Python,编译时间稍长,编译成功后会在/usr/local目录下生成一个名为python3的文件夹,说明Python3安装成功
[root@JetXi local]# cd Python-3.9.2
[root@JetXi Python-3.9.2]# ./configure prefix=/usr/local/python3
[root@JetXi Python-3.9.2]# make && make install
-
查看系统内置Python版本和软链接指向情况,由结果可知,python命令指向python2命令,而python2命令指向python2.7,因此我们将python命令软链接指向刚才安装的Python3即可,这样执行python命令默认进入Python3,执行python2命令进入python2.7
[root@JetXi Python-3.9.2]# ll /usr/bin/python*
lrwxrwxrwx. 1 root root 7 Feb 19 01:11 /usr/bin/python -> python2
lrwxrwxrwx. 1 root root 9 Feb 19 01:11 /usr/bin/python2 -> python2.7
-rwxr-xr-x. 1 root root 7136 Aug 4 2017 /usr/bin/python2.7
-
删除指向python2的python软链接,创建指向Python3的python软链接
[root@JetXi Python-3.9.2]# rm -f /usr/local/python
[root@JetXi local]# ln -s /usr/local/python3/bin/python3.9 /usr/bin/python
-
测试结果是否符合预期
[root@JetXi ~]# python
Python 3.9.2 (default, Feb 21 2021, 07:59:45)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()
[root@JetXi ~]# python2
Python 2.7.5 (default, Aug 4 2017, 00:39:18)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()
-
至此Python3环境已经全部安装完成,但是正如前文所说,yum需要基于Python2运行,因此我们需要对yum的配置文件做一些改动
[root@JetXi ~]# vi /usr/bin/yum
# 将第一行的python改为python2
#! /usr/bin/python2
-
同理,urlgrabber-ext-down也需要修改
[root@JetXi ~]# vi /usr/libexec/urlgrabber-ext-down
# 将第一行的python改为python2
#! /usr/bin/python2
-
若不想做8 9的改动,可以考虑不覆盖python软链接,而是创建一个python3软链接指向Python3
[root@JetXi local]# ln -s /usr/local/python3/bin/python3.9 /usr/bin/python3
-
这样需要输入python3命令使用Python3
[root@JetXi ~]# python3
Python 3.9.2 (default, Feb 21 2021, 07:59:45)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()