You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

M1 Mac下PyInstaller打包Django应用时GDAL库未找到问题

问题

在M1 Mac上使用PyInstaller打包Django应用,运行以下./build.sh脚本:

source .env/bin/activate
pyinstaller backend/manage.py -F \
--name "test" \
--icon='icon.ico' \
--add-data "backend/*:package" \

出现GDAL库找不到的错误:

144 WARNING: Failed to collect submodules for 'django.contrib.gis.utils' because 
importing 'django.contrib.gis.utils' raised: django.core.exceptions.ImproperlyConfigured: 
Could not find the GDAL library (tried "gdal", "GDAL", "gdal3.4.0", "gdal3.3.0", 
"gdal3.2.0", "gdal3.1.0", "gdal3.0.0", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0"). Is GDAL 
installed? If it is, try setting GDAL_LIBRARY_PATH in your settings.

已在settings.py中配置:

GDAL_LIBRARY_PATH = "/opt/homebrew/Cellar/gdal/3.5.2/lib/libgdal.dylib"
GEOS_LIBRARY_PATH = "/opt/homebrew/Cellar/geos/3.11.0/libgeos_c.1.17.0.dylib"

终端查询库信息:

/opt/homebrew/opt/geos/lib/libgeos_c.dylib: Mach-O 64-bit dynamically linked shared library arm64
/opt/homebrew/Cellar/gdal/3.5.2/lib/libgdal.dylib: Mach-O 64-bit dynamically linked shared library arm64

解决方法

1. 打包前显式设置环境变量

PyInstaller打包过程中可能无法直接读取Django配置里的库路径,需在脚本开头添加环境变量声明:
修改后的build.sh:

export GDAL_LIBRARY_PATH="/opt/homebrew/Cellar/gdal/3.5.2/lib/libgdal.dylib"
export GEOS_LIBRARY_PATH="/opt/homebrew/Cellar/geos/3.11.0/libgeos_c.1.17.0.dylib"
source .env/bin/activate
pyinstaller backend/manage.py -F \
--name "test" \
--icon='icon.ico' \
--add-data "backend/*:package" \

2. 手动添加动态库到打包列表

PyInstaller可能自动遗漏GDAL/GEOS动态库,用--add-binary参数强制打包:
更新pyinstaller命令:

pyinstaller backend/manage.py -F \
--name "test" \
--icon='icon.ico' \
--add-data "backend/*:package" \
--add-binary "/opt/homebrew/Cellar/gdal/3.5.2/lib/libgdal.dylib:." \
--add-binary "/opt/homebrew/Cellar/geos/3.11.0/libgeos_c.1.17.0.dylib:." \

注::.表示将库文件打包到可执行文件的根目录,确保运行时能被加载。

3. 重新适配虚拟环境的GDAL绑定

确保虚拟环境中的GDAL绑定是基于M1架构编译的,重新安装依赖:

source .env/bin/activate
pip uninstall -y django gdal
pip install django
pip install GDAL==3.5.2 --global-option=build_ext --global-option="-I/opt/homebrew/Cellar/gdal/3.5.2/include" --global-option="-L/opt/homebrew/Cellar/gdal/3.5.2/lib"

4. 运行时指定库路径(可选)

如果打包后运行仍报错,启动时显式传入环境变量:

GDAL_LIBRARY_PATH=/opt/homebrew/Cellar/gdal/3.5.2/lib/libgdal.dylib GEOS_LIBRARY_PATH=/opt/homebrew/Cellar/geos/3.11.0/libgeos_c.1.17.0.dylib ./dist/test

内容的提问来源于stack exchange,提问作者PolarBear10

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 09:25:40