Python编译升级3.7.x

发布时间 2023-12-11 18:17:48作者: 进宝

CentOS 7自带的Python为3.6.x,但因项目需要,要升级到3.7.x,记录遇到的一些问题。

Python3.7.x需要先升级OpenSSL到1.1.x后的版本,否则会报下面的错误

WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.

1. OpenSSL升级到1.1.x

1.1. 下载解压OpenSSL

OpenSSL 官方下载地址:https://www.openssl.org/source/

tar -zxvf openssl-1.1.1w.tar.gz
cd openssl-1.1.1w

1.2. 编译安装

./config --prefix=/usr/local/openssl
make && make install

1.3. 备份并替换当前系统版本

mv /usr/bin/openssl /usr/bin/openssl.old
mv /usr/lib64/openssl /usr/lib64/openssl.old
mv /usr/lib64/libssl.so /usr/lib64/libssl.so.old
ln -s /usr/local/openssl/bin/openssl /usr/bin/openssl
ln -s /usr/local/openssl/include/openssl /usr/include/openssl
ln -s /usr/local/openssl/lib/libssl.so /usr/lib64/libssl.so
echo "/usr/local/openssl/lib" >> /etc/ld.so.conf
openssl version // 建立动态链接

1.4. 查看OpenSSL版本

openssl version

2. 安装Python 3.7.x

2.1. 下载解压

wget https://www.python.org/ftp/python/3.7.17/Python-3.7.17.tgz
tar -zxvf openssl-1.1.1w.tar.gz
cd Python-3.7.17

2.2. 编译安装

./configure --prefix=/usr/local/python3.7 --with-openssl=/usr/local/openssl
make && make altinstall

2.3. 指定国内镜像源

pip3 config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

3. 其他问题

安装完成后运行脚本,抛出以下异常:

File "/usr/local/python3/lib/python3.7/ctypes/__init__.py", line 7, in <module> from _ctypes importUnion, Structure, Array ModuleNotFoundError: No module named '_ctypes'

原因:Python3中有个内置模块叫ctypes,它是Python3的外部函数库模块,它提供兼容C语言的数据类型,并通过它调用Linux系统下的共享库(Shared library),此模块需要使用CentOS7系统中外部函数库(Foreign function library)的开发链接库(头文件和链接库)。
由于在CentOS7系统中没有安装外部函数库(libffi)的开发链接库软件包,所以在安装pip的时候就报了"ModuleNotFoundError: No module named '_ctypes'"的错误。

yum install libffi-devel
# 然后执行步骤2,重新安装Python

参考

  1. https://github.com/actions/setup-python/issues/93#issuecomment-716433622
  2. https://www.cnblogs.com/fanbi/p/12375023.html
  3. https://www.jianshu.com/p/8e476eef43f7