本文将介绍如何在centos系统通过源码安装python。
本文记录 2023 年安装 Python 3.12.0 的流程,当时没有记下具体的 CentOS 版本。示例中的 OpenSSL 1.1.1o 已停止上游公共维护,新部署请选择仍受支持的系统、Python 和 OpenSSL 版本组合。
Python 3.10 及以上要求 OpenSSL 至少为 1.1.1,而不同 CentOS 版本自带的 OpenSSL 也不同,需要先检查本机环境。下面将 OpenSSL 和 Python 安装到独立目录,保留系统原有的程序和库。
安装独立的openssl
先准备 C 编译器、make 及目标 Python 所需的开发库;具体软件包名随 CentOS 版本变化。Python 3.12 要求支持 C11 的编译器,可按 Python 构建要求 检查环境。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| # 检查默认 openssl which openssl openssl version
# 下载并核对官方提供的校验值,历史示例使用 OpenSSL 1.1.1o # 历史归档与校验值见 https://openssl-library.org/source/old/1.1.1/ wget https://github.com/openssl/openssl/releases/download/OpenSSL_1_1_1o/openssl-1.1.1o.tar.gz tar -xzvf openssl-1.1.1o.tar.gz cd openssl-1.1.1o
# 独立安装;保留发行版的 openssl 和共享库 ./config --prefix=/usr/local/custom-openssl --libdir=lib --openssldir=/etc/pki/tls make && sudo make install_sw cd ..
# 检查新安装的版本,不修改 /usr/bin/openssl LD_LIBRARY_PATH=/usr/local/custom-openssl/lib /usr/local/custom-openssl/bin/openssl version
|
上面的 /etc/pki/tls 是常见的 CentOS 证书配置目录,使用前应确认本机的 openssl.cnf 和系统信任库位置。安装目标使用 install_sw,避免覆盖证书配置;共享库搜索路径只用于上面这一次检查,不设为全局变量。
安装python
在centos系统中下载源码,如下。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| # 历史示例版本;新安装请在 https://www.python.org/downloads/ 选择受支持的补丁版本 wget https://www.python.org/ftp/python/3.12.0/Python-3.12.0.tgz
# 解压 tar -zxvf Python-3.12.0.tgz cd Python-3.12.0
# 编译安装到独立目录,并记录 OpenSSL 库的运行时路径 ./configure --prefix=/usr/local/python3.12.0 --with-openssl=/usr/local/custom-openssl --with-openssl-rpath=auto make && sudo make altinstall
# 测试版本及 ssl 模块 /usr/local/python3.12.0/bin/python3.12 --version /usr/local/python3.12.0/bin/python3.12 -c 'import ssl; print(ssl.OPENSSL_VERSION)'
# 通过这个解释器使用 pip /usr/local/python3.12.0/bin/python3.12 -m pip --version
|
确认所需模块编译成功、上面的检查也通过后,便可以使用这个独立的 Python 啦!项目依赖建议安装在由该解释器创建的虚拟环境中。
参考:Python Unix 安装与 Custom OpenSSL。