python提示"ModuleNotFoundError: No module named '_ssl'"解决

1.编译 OpenSSL

本质: python编译版本依赖ssl不匹配导致的

1
2
3
4
5
cd /usr/local/src

wget https://www.openssl.org/source/openssl-1.1.1w.tar.gz
tar xf openssl-1.1.1w.tar.gz
cd openssl-1.1.1w

编译:

1
2
3
4
./config --prefix=/usr/local/openssl-1.1 \
--openssldir=/usr/local/openssl-1.1
make -j$(nproc)
make install

配置动态库:

1
2
echo "/usr/local/openssl-1.1/lib" > /etc/ld.so.conf.d/openssl-1.1.conf
ldconfig

验证:

1
/usr/local/openssl-1.1/bin/openssl version

应该看到:

OpenSSL 1.1.1w

2.重新编译 Python

先清理旧编译:

1
2
cd /usr/local/src/Python-3.9.19
make clean

配置:

1
2
3
4
5
./configure \
--prefix=/usr/local/python3.9 \
--enable-optimizations \
--enable-shared \
--with-openssl=/usr/local/openssl-1.1

编译:

1
2
make -j$(nproc)
make install

配置库路径:

1
2
echo "/usr/local/python3.9/lib" > /etc/ld.so.conf.d/python3.9.conf
ldconfig

3.验证 ssl

1
/usr/local/python3.9/bin/python3.9 -c "import ssl; print(ssl.OPENSSL_VERSION)"

正常会看到:

OpenSSL 1.1.1w

然后再试:

1
pip3 install requests

就不会再出现:

urllib3 v2 only supports OpenSSL 1.1.1+

总结

CentOS7 上编译 Python,99% 稳定方案是:

gcc >= 7
openssl >= 1.1
python >= 3.9

依赖关系像这样:

graph TD
GCC --> OpenSSL
OpenSSL --> Python_ssl_module
Python_ssl_module --> requests
requests --> urllib3

任何一层太旧,都会出现奇怪报错。