python3虚拟环境中解决 ModuleNotFoundError: No module named '_ssl'
前提是已经安装了openssl
问题
当我在python3虚拟环境中导入ssl模块时报错,报错如下:
(py3) [root@localhost Python-3.6.3]# python3
Python 3.6.3 (default, Nov 19 2018, 14:18:18)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import ssl
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/python3/lib/python3.6/ssl.py", line 101, in <module>
import _ssl # if we can't import it, let the error propagate
ModuleNotFoundError: No module named '_ssl'
解决办法如下:
1.首先进入Python-3.6.3目录,就是你解压后安装python3.6的目录文件。
2. cd 到 Modules 目录里,找到Setup和Setup.dist文件,将下面几行注释去掉。
-
Setup下更改
-
vim Setup (大概在51%的位置)
-
Setup.dist下的更改
-
vim Setup.dist (大概在50%的位置)
3.编译安装
cd ..
./configure --prefix=/usr/local/python3
make
make install
4.删除旧的软连接,创建新的软连接(很重要)
rm -rf /usr/bin/python3
ln -s /usr/local/bin/python3.6 /usr/bin/python3
5、删除之前的虚拟环境,重新创建一个新的虚拟环境,导入ssl包就ok了
# 删除之前建议先将之前的安装的包导出
# 进入虚拟环境
source py3/bin/activate
# 备份文件
pip freeze > requirements.txt
# 退出虚拟环境
deactivate
# 删除虚拟环境
rm -rf py3
# 创建新的虚拟环境
virtualenv py3 -p /usr/bin/python3
# 进入到新的虚拟环境中
source py3/bin/activate
# 导入ssl包
(py3) [root@localhost /]# python
Python 3.6.3 (default, Nov 21 2018, 22:23:54)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import ssl
>>>
# 恢复之前的python环境
pip install -r requirements.txt
若用到uwsgi,且需要import ssl,则需要把之前uwsgi卸载,重新编译安装
pip3 uninstall uwsgi
sudo pip3 install uwsgi -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
# 删除原来的软链接,设置新的软链接
sudo ln -s /usr/local/python3/bin/uwsgi /usr/bin/uwsgi