Windows QGIS 中 ImportError: DLL load failed while importing _C 的解決方法
ImportError: DLL load failed while importing _C in QGIS on Windows
從 aka.ms/vs/17/release/vc_redist.x64.exe 安裝 Microsoft Visual C++ Redistributable (x64),然後重新啟動 Windows。PyTorch 隨附需要 Microsoft C runtime 的已編譯 DLL,若該 runtime 遺失或版本過舊,Windows 就會拒絕載入這些 DLL。
Traceback (most recent call last):
File "C:\...\site-packages\torch\__init__.py", line 141, in <module>
raise err
OSError: [WinError 126] The specified module could not be found.
Error loading "C:\...\site-packages\torch\lib\fbgemm.dll" or one of its dependencies.
ImportError: DLL load failed while importing _C: The specified module could not be found.
適用於 Windows 10 和 11、QGIS 3.22 及更新版本,以及任何安裝在 QGIS Python 或 plugin 環境中的 PyTorch 2.x。
發生原因
四個原因會印出相同的一行。以下順序是它們最後被確認為真正原因的常見順序:
- Visual C++ Redistributable (x64) 遺失或版本過舊。
fbgemm.dll和其他 torch DLL 都會連結到它。 - 電腦上有第二個 Python(Anaconda、Miniconda 或獨立安裝版本),將自己的 torch DLL 放在 Windows 優先找到的位置。從 Python 3.8 開始,extension DLL 會透過
os.add_dll_directory()取得,而混用的設定會註冊錯誤的資料夾。 - 已安裝的 wheel 與電腦不相容。在沒有相符 NVIDIA driver 的電腦上使用 CUDA build,也會以相同方式失敗。
- 防毒軟體或企業應用程式控管政策,在安裝完成後隔離了某個
.pyd或.dll。
要區分這些原因,請在 Command Prompt 中執行 where python。出現多個結果通常指向原因 2。只有一個結果,而重新安裝 redistributable 並重新啟動後錯誤仍然存在,則指向原因 3 或 4。
解決方法
Install the Visual C++ Redistributable (x64)
從 Microsoft 下載 vc_redist.x64.exe 並執行。即使電腦也安裝了 x86 版本,仍要選擇 x64 build。
Restart Windows
重新啟動 Windows,而不只是重新啟動 QGIS。DLL 搜尋清單會在每個程序中讀取一次,而安裝程式通常會留下需要在重新啟動時完成的工作。
Test the import on its own
從開始功能表的 QGIS 資料夾開啟 OSGeo4W Shell,然後執行 python -c "import torch"。出現乾淨的提示字元就表示成功。在 QGIS 內,相同的測試路徑是 Plugins,接著 Python Console,然後執行 import torch。
Remove the second Python from PATH
如果 where python 回傳了多個路徑,請開啟 Start,輸入 "environment variables",開啟 Edit the system environment variables,接著選擇 Environment Variables,再選擇 Path。移除屬於你不在 QGIS 中使用之 Python 的項目。登出後再重新登入。
Reinstall the wheel that matches the machine
在沒有 NVIDIA GPU 的電腦上,強制使用 CPU build:pip install --force-reinstall torch --index-url https://download.pytorch.org/whl/cpu。如果有 GPU,請使用 PyTorch install page 針對你的 CUDA 版本提供的指令。
如果仍然無法運作
- 有些電腦已安裝 redistributable,卻仍缺少一個相依項目
libomp140.x86_64.dll。它會隨 Visual Studio Community 一起安裝,這是免費安裝項目。不要從下載網站下載單獨的 DLL。 - 開啟 Windows Security,接著選擇 Virus and threat protection,再選擇 Protection history。還原它從你的
site-packages資料夾移除的任何檔案,並在重新安裝前將該資料夾加入排除項目。 - 在 conda 環境中,請使用 conda 而不是 pip 安裝 torch,讓 runtime libraries 與套件來自同一處。

