Never too late to learn.

0%

CentOS 安装 Python3

​ CentOS 7附带了Python 2.7.5,这是CentOS基本系统的关键部分。而Python 2在2020年将不在支持,大势所趋,对于python开发而言,推荐使用python3,本文根据网络资源,通过实践,在CentOS 7上安装Python3。

0. 系统环境

1
2
3
4
5
6
$ lsb_release -a
LSB Version: :core-4.1-amd64:core-4.1-noarch
Distributor ID: CentOS
Description: CentOS Linux release 7.5.1804 (Core)
Release: 7.5.1804
Codename: Core

1. 查看python2位置

1
2
$ whereis python
python: /usr/bin/python /usr/bin/python2.7 /usr/lib/python2.7 /usr/lib64/python2.7 /etc/python /usr/include/python2.7 /usr/share/man/man1/python.1.gz
1
2
3
4
5
6
$ cd /usr/bin

$ ll python*
lrwxrwxrwx 1 root root 7 Oct 18 2018 python -> python2
lrwxrwxrwx 1 root root 9 Oct 18 2018 python2 -> python2.7
-rwxr-xr-x 1 root root 7216 Jul 13 2018 python2.7

2. 安装编译python3的相关包

1
2
$ cd
$ yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gcc make libffi-devel

3. 安装epel扩展源和pip

1
2
3
$ yum -y install epel-release 

$ yum install python-pip (# if pip not exist)

4. 用pip安装wget

1
$ pip install wget

5. 下载python3.7.4源码包, 解压安装(需要较高权限)

1
2
3
4
5
6
7
$ wget https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tgz

$ tar -zxvf Python-3.7.4.tgz

$ cd Python-3.7.4

$ make && make install

make时出现错误:make: *** No targets specified and no makefile found. Stop.
在当前目录下,先运行./configure,生成makefile,再执行make

./configure

安装成功后在/usr/bin/下会有python3目录

6. (可选)添加软链接

1
2
$ ln -s /usr/local/python3/bin/python3.7 /usr/bin/python3
$ ln -s /usr/local/python3/bin/pip3.7 /usr/bin/pip3
1
2
3
4
5
6
7
8
9
10
11
12
13
$ cd /usr/bin

$ ll python*
lrwxrwxrwx 1 root root 7 Oct 18 2018 python -> python2
lrwxrwxrwx 1 root root 9 Oct 18 2018 python2 -> python2.7
-rwxr-xr-x 1 root root 7216 Jul 13 2018 python2.7
lrwxrwxrwx 1 root root 32 Oct 10 17:58 python3 -> /usr/local/python3/bin/python3.7

$ ll pip*
-rwxr-xr-x 1 root root 282 Aug 12 19:18 pip
-rwxr-xr-x 1 root root 284 Aug 12 19:18 pip2
-rwxr-xr-x 1 root root 288 Aug 12 19:18 pip2.7
lrwxrwxrwx 1 root root 29 Oct 10 17:59 pip3 -> /usr/local/python3/bin/pip3.7
1
2
3
4
5
$ python -V
Python 2.7.5

$ python3 -V
Python 3.7.4

7.(可选)更改yum配置

如果在第6步中设置的软连接为/usr/bin/python,即替换了原来的python命令的指向,则

1
2
$ python -V
Python 3.7.4

yum需要python2的执行,因此需要修改yum配置

1
2
3
4
vi /usr/bin/yum 
#! /usr/bin/python 修改为 #! /usr/bin/python2
vi /usr/libexec/urlgrabber-ext-down
#! /usr/bin/python 修改为 #! /usr/bin/python2
Coffee? ☕