Description
如题描述,当前在本地高版本的 macos 电脑上,通过直接命令行方式:
pyenv install 3.10
安装 python 提示报错失败:
Error The Python ssl extension was not compiled. Missing the OpenSSL lib?
完整报错路下:
❯ pyenv install 3.10
python-build: use openssl@1.1 from homebrew
python-build: use readline from homebrew
Downloading Python-3.10.12.tar.xz...
-> https://www.python.org/ftp/python/3.10.12/Python-3.10.12.tar.xz
Installing Python-3.10.12...
python-build: use readline from homebrew
python-build: use zlib from homebrew
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/Users/xxx/.pyenv/versions/3.10.12/lib/python3.10/ssl.py", line 99, in <module>
import _ssl # if we can't import it, let the error propagate
ModuleNotFoundError: No module named '_ssl'
ERROR: The Python ssl extension was not compiled. Missing the OpenSSL lib?
Please consult to the Wiki page to fix the problem.
https://github.com/pyenv/pyenv/wiki/Common-build-problems
BUILD FAILED (OS X 13.0 using python-build 20180424)
Inspect or clean up the working tree at /var/folders/5t/c55_bg3128l0z7rfj_9w6cdc0000gn/T/python-build.20231218134935.47338
Results logged to /var/folders/5t/c55_bg3128l0z7rfj_9w6cdc0000gn/T/python-build.20231218134935.47338.log
Last 10 log lines:
DYLD_LIBRARY_PATH=/var/folders/5t/c55_bg3128l0z7rfj_9w6cdc0000gn/T/python-build.20231218134935.47338/Python-3.10.12 ./python.exe -E -m ensurepip \
$ensurepip --root=/ ; \
fi
Looking in links: /var/folders/5t/c55_bg3128l0z7rfj_9w6cdc0000gn/T/tmphjw758g_
Processing /private/var/folders/5t/c55_bg3128l0z7rfj_9w6cdc0000gn/T/tmphjw758g_/setuptools-65.5.0-py3-none-any.whl
Processing /private/var/folders/5t/c55_bg3128l0z7rfj_9w6cdc0000gn/T/tmphjw758g_/pip-23.0.1-py3-none-any.whl
Installing collected packages: setuptools, pip
WARNING: The scripts pip3 and pip3.10 are installed in '/Users/xxx/.pyenv/versions/3.10.12/bin' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed pip-23.0.1 setuptools-65.5.0
Root Cause
虽然 homebrew 已经提示安装了 ssl, 但是实际上并未真正成功安装。
而且对应的 ssl 的代码路径有些不一样,需要对齐调整,具体详情看 # solution.
Solution
同时注意,需要特别设定编译变量 CFLAGS 和 CFLAGS。
其中
CFLAGS="-I$(brew --prefix openssl)/include"
: 这里设置了环境变量 CFLAGS,用于告诉编译器在哪里寻找头文件。-I 选项后面跟着的是头文件的路径,这里使用 $(brew --prefix openssl) 获取 OpenSSL 的安装路径,然后添加 /include 子目录,表示 OpenSSL 的头文件所在的路径。
LDFLAGS="-L$(brew --prefix openssl)/lib"
: 这里设置了环境变量 LDFLAGS,用于告诉链接器在哪里寻找库文件。-L 选项后面跟着的是库文件的路径,这里同样使用 $(brew --prefix openssl) 获取 OpenSSL 的安装路径,然后添加 /lib 子目录,表示 OpenSSL 的库文件所在的路径。
卸载掉 ssl 并重新安装,再继续通过pyenv 安装 python 即可.
brew uninstall openssl && brew install openssl && CFLAGS="-I$(brew --prefix openssl)/include" LDFLAGS="-L$(brew --prefix openssl)/lib" pyenv install ${python version}
example:
brew uninstall openssl && brew install openssl && CFLAGS="-I$(brew --prefix openssl)/include" LDFLAGS="-L$(brew --prefix openssl)/lib" pyenv install 3.10.12