Fixing PyQGIS Module Import Errors
ModuleNotFoundError: No module named 'qgis' and ImportError: DLL load failed occur when your Python interpreter runs outside QGIS’s managed environment. Fixing PyQGIS module import errors requires either injecting QGIS library paths at runtime or executing your script through the QGIS-bundled Python executable.
Quick Fix: Manual Path Injection
When running scripts externally (VS Code, PyCharm, standalone terminal), inject QGIS paths before any qgis imports. Place this block at the top of your script:
import sys
import os
# Update to match your exact QGIS installation
QGIS_PREFIX = r"C:\Program Files\QGIS 3.34" # Windows Standalone
# QGIS_PREFIX = "/Applications/QGIS.app/Contents/MacOS" # macOS
# QGIS_PREFIX = "/usr" # Linux (Debian/Ubuntu)
# Inject QGIS Python paths (order matters)
sys.path.insert(0, os.path.join(QGIS_PREFIX, "apps", "qgis", "python"))
sys.path.insert(0, os.path.join(QGIS_PREFIX, "apps", "qgis", "python", "plugins"))
# Set mandatory environment variables
os.environ["QGIS_PREFIX_PATH"] = QGIS_PREFIX
os.environ["PATH"] = os.path.join(QGIS_PREFIX, "bin") + os.pathsep + os.environ.get("PATH", "")
# Initialize QGIS application context
from qgis.core import QgsApplication
QgsApplication.setPrefixPath(QGIS_PREFIX, True)
QgsApplication.initQgis()
print("PyQGIS environment loaded successfully.")
Note: PYTHONHOME is intentionally omitted. Setting it in external environments frequently breaks virtual environments and triggers silent crashes.
Critical Compatibility Rules
- Python Version Alignment: PyQGIS bindings are compiled against a specific Python ABI. QGIS 3.28 uses Python 3.9, 3.32+ uses 3.10, and 3.34+ uses 3.11. Running an external Python 3.12 interpreter against QGIS 3.28 will immediately fail with
ImportError. Always match your external interpreter to the QGIS release. - OS Path Variations: Windows standalone uses
apps/qgis/python. OSGeo4W requiresC:\OSGeo4W\apps\qgis-ltr\python. macOS bundles binaries inside.app/Contents/Resources/python. Linux package managers typically handle symlinks automatically, making manual injection unnecessary unless using isolatedvenvenvironments. - Architecture Mismatch: Modern PyQGIS is strictly 64-bit. Loading it with a 32-bit Python interpreter will fail on
QgsApplicationinitialization. - IDE Isolation: PyCharm and VS Code often activate isolated virtual environments that strip inherited system paths. If your IDE configuration feels opaque, reviewing PyQGIS Fundamentals & Environment Setup will help you correctly map interpreter inheritance and site-packages.
Fallbacks When Path Injection Fails
If sys.path injection throws ImportError: cannot import name 'QgsApplication' or crashes, switch to these proven alternatives:
- Execute via QGIS Python Wrapper Bypass external interpreters by calling the bundled executable directly:
- Windows:
"C:\Program Files\QGIS 3.34\bin\python-qgis.bat" your_script.py - macOS:
/Applications/QGIS.app/Contents/MacOS/bin/python3 your_script.py - Linux:
qgis --code your_script.py
- Run Inside the QGIS Python Console
Open QGIS → Plugins → Python Console. Paste your logic or run
exec(open('your_script.py').read()). The console auto-initializesQgsApplicationand loads allqgis.*namespaces. - Remove Conflicting PyPI Packages
Run
pip list | grep qgis(macOS/Linux) orpip list | findstr qgis(Windows). If you see an unrelatedqgispackage, uninstall it immediately:pip uninstall qgis. Official PyQGIS bindings are never distributed via PyPI and will shadow the correct libraries. - Verify Native Dependency Chains
PyQGIS relies on compiled C++ libraries (GDAL, PROJ, Qt).
DLL load failed while importing _coreusually indicates missing Visual C++ Redistributables (Windows) or mismatched GDAL binaries. Repair your QGIS installation or run the OSGeo4W installer in repair mode to restore native dependencies.
For persistent runtime crashes or silent failures during plugin execution, structured logging and step-through inspection are essential. Consult Debugging PyQGIS Scripts to isolate stack traces and validate environment states before deploying to production pipelines.