本文基于以下环境展开:
Linux: Linux version 3.10.0-862.14.4.el7.x86_64 (mockbuild@kbuilder.bsys.centos.org) (gcc version 4.8.5 20150623 (Red Hat 4.8.5-28) (GCC) )
Python: v3.6.8
问题描述
linux 上用源码安装 python3.6.8 后,在使用过程中,出现错误:
ImportError: No module named _ssl
解决方法
删除原先编译的包,修改配置重新开始,如下:
-
安装依赖包
yum install -y libffi-devel zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel zlib zlib-devel gcc make
-
将下载好的 python 包 解压
# 本文以 Python-3.6.8.tgz 为例, 可自行将其替换 tar -xzf Python-3.6.8.tgz
-
进入解压文件夹,并修改配置
cd Python-3.6.8 # 1.修改 setup.py 配置 search_for_ssl_incs_in = [ '/usr/local/ssl/include', '/usr/contrib/ssl/include/', '/usr/local/ssl/include/openssl', # 添加此行,否则可能会报错找不到 rsa.h 文件 ] # 2.修改 Modules/Setup.dist 配置 # 取消 line:209-2011 注释 # Socket module helper for SSL support; you must comment out the other # socket line above, and possibly edit the SSL variable: SSL=/usr/local/ssl _ssl _ssl.c \ -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \ -L$(SSL)/lib -lssl -lcrypto
注: 在修改 setup.py 和 Modules/Setup.dist 时需要提前确认 /usr/local/ssl 存在, 若不存在则按步骤7安装
-
编译 & 安装
mkdir /usr/local/python36 ./configure --prefix=/usr/local/python36 make && make install
-
建立软链
ln -s /usr/local/python36/bin/python3.6 /usr/bin/python36
-
验证是否成功
# 命令行输入 python36 并 import ssl, 如下则成功 Python 3.6.8 (default, Jun 24 2020, 00:11:17) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import ssl >>>
-
下载并安装 openssl
# 获取安装包 wget http://www.openssl.org/source/openssl-1.0.2j.tar.gz # 解压 tar -xzf openssl-1.0.2j.tar.gz # 编译 & 安装 ./config # 若不指定 --prefix, 则会在 /usr/local 下生成 ssl; 若指定,步骤3中的路径也要进行相应的改变 make && make install