Python3.12及更高版本下如何用MinGW GCC编译Pip无Wheel包?
问题场景
已配置MinGW和distutils,Cython编译扩展正常,但安装无预编译Wheel的包(如PyQt6-sip)时,仍弹出以下错误:
exit code: 1
[5 lines of output]
running bdist_wheel
running build
running build_ext
building 'PyQt6.sip' extension
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
[end of output]note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for PyQt6-sip
Failed to build PyQt6-sip
ERROR: ERROR: Failed to build installable wheels for some pyproject.toml based projects (PyQt6-sip)
旧方案(修改Python安装目录下\Lib\distutils配置)因Python3.12+移除该目录失效,而setuptools+Cython场景已通过--compiler=mingw32解决,现需适配Python3.12+的通用解决方案。
解决方案
方案1:安装时直接传递编译参数
针对单个包安装,使用--config-settings参数将编译器指定为mingw32,适配pyproject.toml格式的项目:
pip install PyQt6-sip --config-settings "--build-option=--compiler=mingw32"
若需传递多个构建选项,可用分号分隔:
pip install PyQt6-sip --config-settings "--build-option=--compiler=mingw32;--build-option=--some-other-option"
方案2:全局配置默认编译器
避免每次安装都输入参数,可通过用户目录下的distutils配置文件全局指定编译器:
- 在用户目录创建
distutils文件夹(路径示例:C:\Users\你的用户名\distutils) - 在该文件夹内创建
distutils.cfg文件,写入以下内容:
[build] compiler=mingw32
- 确保MinGW的
bin目录已添加到系统PATH环境变量中(如C:\MinGW\bin)
方案3:设置环境变量强制使用MinGW
临时或全局设置以下环境变量,让setuptools优先调用MinGW:
- 临时生效(仅当前命令行窗口):
set SETUPTOOLS_USE_DISTUTILS=local set DISTUTILS_USE_SDK=1
执行完上述命令后再运行pip安装即可。
- 全局生效:在系统环境变量中添加上述两个变量。
原理说明
Python3.12+移除了标准库中的distutils模块,当前distutils作为setuptools的内置组件提供。旧方案修改Python安装目录下Lib\distutils的配置已失效,需通过用户级配置或传递参数的方式,让setuptools调用的distutils使用MinGW编译器,替代对VC++ Build Tools的依赖。
内容的提问来源于stack exchange,提问作者zamkorus

