QGIS Windows 中匯入 _gdal 時的 ImportError: DLL load failed 解決方法
ImportError: DLL load failed while importing _gdal in QGIS on Windows
PATH 中存在第二份 GDAL,Windows 載入的是它的 DLL,而不是 QGIS 的 DLL。找出含有 gdal*.dll 的資料夾,將非 QGIS 的資料夾從 PATH 移除,然後登出 Windows 再重新登入。
ImportError: DLL load failed while importing _gdal: The specified module could not be found.
On Windows, with Python >= 3.8, DLLs are no longer imported from the PATH.
If gdalXXX.dll is in the PATH, then set the USE_PATH_FOR_GDAL_PYTHON=YES environment variable
to feed the PATH into os.add_dll_directory().
適用於 Windows、QGIS 3.16 及更新版本,以及任何匯入 from osgeo import gdal 的 Python 3.8 或更新版本。同一個錯誤也會在 QGIS 的 Log Messages 面板中顯示為 "Couldn't load plugin 'processing'"。
為什麼會發生
最後三行是 GDAL 在匯入失敗時印出的提示。它們不是原因,所以設定該變數通常不會有任何作用。
Python 3.8 開始不再搜尋 PATH 中的擴充 DLL。GDAL 的 osgeo/__init__.py 會繞過這項限制:它會逐一檢查 PATH,對每個含有 gdal*.dll 或 libgdal*.dll 的資料夾呼叫 os.add_dll_directory()。Microsoft 沒有保證以這種方式加入的資料夾之間有固定順序,因此同時存在兩份 GDAL 時,錯誤的版本可能會搶先載入,而它的 DLL 與 QGIS 隨附的 _gdal 模組不相容。第二個原因比較少見:從 QGIS 環境外執行一般的 python.exe 或 PyCharm,完全沒有註冊 GDAL 資料夾。第三個原因是 OSGeo4W 更新不完整,同時保留了 gdal 和 gdal-dev。
要區分這些情況,請執行步驟 1 的檢查。顯示兩個以上資料夾表示是第一個原因。顯示零個資料夾表示是第二個原因。
修正方法
List every folder on PATH that holds a GDAL DLL
從開始選單的 QGIS 資料夾開啟 OSGeo4W Shell,然後執行以下指令。它會重現 GDAL 自己使用的邏輯:
python -c "import os,glob;print('\n'.join(p for p in os.environ['PATH'].split(';') if p and (glob.glob(os.path.join(p,'gdal*.dll')) or glob.glob(os.path.join(p,'libgdal*.dll')))))"
Remove the copies that are not QGIS
Anaconda、Miniconda、第二個 QGIS 或 OSGeo4W 安裝,或其他會將自有 GDAL 放入 PATH 的 GIS 套件。開啟開始選單,輸入 "environment variables",開啟 Edit the system environment variables,接著選擇 Environment Variables,再選擇 Path。刪除這些項目。登出 Windows 再重新登入,讓每個程序都取得新的 PATH。
Start QGIS from its own shortcut
不要從已經執行其他環境 activate 指令的 Shell 開啟,也不要從第二個 OSGeo4W Shell 工作階段開啟。設定了 gdal-dev 路徑的 Shell 會將它傳給 QGIS。
For an outside interpreter, borrow the QGIS environment
在 OSGeo4W Shell 中執行你的腳本,或透過 QGIS bin 資料夾中的 python-qgis.bat 執行。這會在 Python 啟動前註冊正確的 DLL 資料夾。
如果這樣仍然無法運作
- 設定該變數,但不要抱太大期待。在 QGIS 中依序選擇 Settings、Options、System,再找到 Environment 群組。勾選自訂變數選項,新增
USE_PATH_FOR_GDAL_PYTHON,值設為YES,然後重新啟動 QGIS。當正確的資料夾位於 PATH 中且沒有其他版本競爭時,它會有所幫助。但同時存在兩份 GDAL 時則沒有作用。 - 在 conda 中,只在全新的環境裡從 conda-forge 安裝
gdal,不要將 pip GDAL wheel 混用其中。 - 修復安裝:重新執行 OSGeo4W 安裝程式並重新安裝
gdal和qgis套件,或使用獨立安裝程式重新安裝 QGIS。這是擺脫更新不完整的 OSGeo4W 最快的方法。

