1. 程式人生 > >python3虛擬環境中解決 ModuleNotFoundError: No module named '_ssl'

python3虛擬環境中解決 ModuleNotFoundError: No module named '_ssl'

當我在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下更改
  • Setup.dist下的更改

3.編譯安裝

./configure --prefix=/usr/local/python
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

完畢!