CentOS 7 默认仓库中的 Python 版本较旧(如 Python 2.7 或 3.6),无法满足现代应用对 Python 3.9+ 版本的需求。通过源码编译安装,可以自定义安装路径、开启特定功能(如 SSL 支持),并获得更高版本的 Python 环境。本文提供 CentOS 7 环境下从源码编译安装 Python 3.9.9 的完整步骤。
核心内容包括:
环境准备:
gcc、libffi-devel、openssl-devel、zlib-devel、bzip2-devel 等源码下载与解压:
Python-3.9.9.tar.xz(或 3.11.10 版本)/usr/local 目录编译配置:
./configure --with-ssl --prefix=/usr/local/python3:开启 SSL 支持,避免 pip3 install 出现 SSL 异常make && make install 完成编译安装环境变量配置:
/etc/profile.d/python3.sh,设置 PYTHON_HOME 和 PATHsource /etc/profile 使配置生效验证与加速:
python3 -V~/.pip/pip.conf),加速 pip 下载本文适用于需要在 CentOS 7 上部署 Python 3.9+ 开发或运行环境的运维及开发人员。
shellcurl -O https://oss.odboy.cn/blog/files/Python-3.9.9.tar.xz
#curl -O https://oss.odboy.cn/blog/files/Python-3.11.10.tar.xz
避免关键时刻命令不存在, 最好按顺序执行~
shellmv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo_bak curl http://mirrors.aliyun.com/repo/Centos-7.repo > /etc/yum.repos.d/CentOS-Base.repo curl http://mirrors.aliyun.com/repo/epel-7.repo > /etc/yum.repos.d/epel.repo sed -i -e '/mirrors.cloud.aliyuncs.com/d' -e '/mirrors.aliyuncs.com/d' /etc/yum.repos.d/CentOS-Base.repo sed -i -e '/mirrors.cloud.aliyuncs.com/d' -e '/mirrors.aliyuncs.com/d' /etc/yum.repos.d/epel.repo yum makecache fast yum install gcc patch libffi-devel python-devel zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel netstat lrzsz unzip zip sysstat ntpdate net-tools -y yum install epel-release -y
shell# 切换到目录'/usr/local'
cd /usr/local
# 上传源码包'Python-3.9.9.tar.xz'到目录'/usr/local'下
rz
# 解压'Python-3.9.9.tar.xz'
tar -xvf Python-3.9.9.tar.xz
# 切换到目录'Python-3.9.9'
cd Python-3.9.9
# 配置、编译、安装(有点漫长, 稍等片刻~)
# ./configure --prefix=/usr/local/python3
# 如果pip3 install出现ssl异常, 那么就换成以下语句重新编译
./configure --with-ssl --prefix=/usr/local/python3
make && make install
# 退回上一层, 删除解压后的源码目录(防止误覆盖)
cd ..
rm -rf Python-3.9.9
# 配置环境变量
echo 'export PYTHON_HOME=/usr/local/python3' > /etc/profile.d/python3.sh
echo 'PATH=$PATH:$PYTHON_HOME/bin' >> /etc/profile.d/python3.sh
# 配置生效
source /etc/profile
# 检查python3安装情况
[root@localhost local]# python3 -V
Python 3.9.9
# 配置阿里源
mkdir ~/.pip
cat > ~/.pip/pip.conf <<EOF
[global]
index-url = https://mirrors.aliyun.com/pypi/simple
[install]
trusted-host = mirrors.aliyun.com
EOF


本文作者:Odboy
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC 4.0 BY-SA 许可协议。转载请注明出处!