如何基于非标准路径的OpenSSL 3.0编译Python 3.11?
问题背景
已在非标准路径/some/dir源码编译安装OpenSSL 3.0.7:
$ wget https://github.com/openssl/openssl/archive/refs/tags/openssl-3.0.7.tar.gz $ tar -xvf openssl-3.0.7.tar.gz $ cd openssl-openssl-3.0.7/ $ ./Configure CC=clang --prefix=/some/dir --openssldir=/some/dir '-Wl,-rpath,$(LIBRPATH)'
随后基于该OpenSSL编译Python3.11.1:
$ wget https://www.python.org/ftp/python/3.11.1/Python-3.11.1.tgz $ tar -xvf Python-3.11.1.tgz $ cd Python-3.11.1/ $ ./configure CC=clang --with-openssl-rpath=auto --with-openssl=/some/dir
configure检测结果显示:
checking for openssl/ssl.h in /some/dir... yes checking whether compiling and linking against OpenSSL works... yes checking for --with-openssl-rpath... auto checking whether OpenSSL provides required ssl module APIs... no checking whether OpenSSL provides required hashlib module APIs... no ...
执行make时出现错误:
$ make ... The necessary bits to build these optional modules were not found: _hashlib _ssl _tkinter To find the necessary bits, look in setup.py in detect_modules() for the module's name. Could not build the ssl module! Python requires a OpenSSL 1.1.1 or newer Custom linker flags may require --with-openssl-rpath=auto
目前hashlib可正常使用(依赖内置实现),但ssl模块无法导入:
>>> import ssl Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/some/dir/Python-3.11.1/Lib/ssl.py", line 100, in <module> import _ssl # if we can't import it, let the error propagate ^^^^^^^^^^^ ModuleNotFoundError: No module named '_ssl'
解决步骤
问题核心是OpenSSL编译参数不匹配、Python编译时环境变量未正确指向OpenSSL路径,导致链接检测失败。按以下步骤修复:
1. 重新编译OpenSSL 3.0.7(生成共享库并配置rpath)
清理之前的编译残留,重新配置编译参数,确保生成动态共享库,同时指定rpath:
cd openssl-openssl-3.0.7/ make clean # 关键添加enable-shared参数确保生成动态库;直接将rpath参数写入Configure命令 ./Configure CC=clang --prefix=/some/dir --openssldir=/some/dir enable-shared -Wl,-rpath=/some/dir/lib make -j$(nproc) # 多线程编译加快速度 make install
注意:如果你的系统库路径是
lib64(如部分Linux发行版),将/some/dir/lib替换为/some/dir/lib64。
2. 设置Python编译所需的环境变量
确保Python的configure能正确找到OpenSSL的头文件和库文件:
export CPPFLAGS="-I/some/dir/include" export LDFLAGS="-L/some/dir/lib -Wl,-rpath=/some/dir/lib" # 同样,lib路径为lib64时替换为/some/dir/lib64
3. 重新编译Python 3.11.1
清理之前的编译残留,重新配置并编译:
cd Python-3.11.1/ make clean ./configure CC=clang --with-openssl=/some/dir --with-openssl-rpath=auto make -j$(nproc) make install
4. 验证结果
编译完成后,启动Python验证ssl模块是否正常导入:
>>> import ssl >>> ssl.OPENSSL_VERSION 'OpenSSL 3.0.7 1 Nov 2022' # 显示对应版本即成功
内容的提问来源于stack exchange,提问作者user14717
相关产品推荐
相关产品推荐

