Setting Up Pythonpath And Path To Import Pyqgis Libraries In Standalone Scripts

Running QGIS processing algorithms and plugins from the graphical user interface is convenient, but tapping into the full capabilities of the PyQGIS libraries requires setting up standalone scripts. A common headache when getting started is wrestling with import errors and module not found issues. Configuring the PYTHONPATH and PATH environment variables is key for scripting success.

The Problem of Importing PyQGIS Libraries

Overview of the Common Import Error Messages and Why They Occur

Attempting to import PyQGIS modules like qgis.core or qgis.analysis often produces errors like:

ModuleNotFoundError: No module named 'qgis'

This occurs because Python cannot locate the QGIS libraries when running outside of the QGIS Python console. The interpreter needs help through PYTHONPATH and PATH variables to find the relevant directories.

Explaining PYTHONPATH and PATH Environment Variables

PYTHONPATH contains directories Python searches through when importing modules, while PATH handles executable program paths. Most QGIS installations do not automatically configure these variables for standalone usage. Understanding how to set them up properly for accessing PyQGIS libraries enables writing scripts that harness QGIS algorithms and classes.

Configuring Environment Variables

Setting up PYTHONPATH on Windows and Linux

PYTHONPATH is populated with a semicolon separated list of paths on Windows, and colon separation on Linux. Here is an example batch file to set it up before launching Python:

@echo off
SET PYTHONPATH=C:\OSGeo4W64\apps\qgis\python;C:\OSGeo4W64\apps\Python37

The equivalent Linux bash script:

export PYTHONPATH=/usr/share/qgis/python:/usr/local/lib/python3.6/site-packages

Adding QGIS Library Paths to PYTHONPATH

The exact QGIS Python library paths vary by platform and installation method, but generally include:

  • /usr/share/qgis/python
  • C:\OSGeo4W64\apps\qgis\python
  • C:\Program Files\QGIS 3.22\apps\Python39\lib

Sometimes additional Python site-packages directories need appending as well. Start by adding the core qgis paths, then tweak as necessary until the imports resolve.

Appending QGIS ‘bin’ Directory to System PATH

The qgis_process and processing algorithm imports can fail without the QGIS bin directory being available. Add it to PATH with similar syntax as PYTHONPATH:

@echo off
SET PATH=%PATH%;C:\OSGeo4W64\apps\qgis\bin

On Linux:

export PATH=$PATH:/usr/share/qgis/bin

Example Scripts and Code Snippets

Importing PyQGIS Libraries and Checking Versions

With PYTHONPATH and PATH set up, PyQGIS libraries can now be imported:

import qgis.core

Suggested imports for access to key QGIS functions:

  • qgis.core – Classes for layer, feature, geometry handling
  • qgis.analysis – Geoprocessing algorithms
  • qgis.utils – Tools for I/O, spatial references

Loading Layers and Basic Data Access/Updates

Create layer instances from vectors or rasters using built-in data providers. Update attribute values or geometries with direct layer access:

layer = QgsVectorLayer('/home/data/ports.gpkg','ports','ogr')

layer.dataProvider().changeAttributeValues( { 0: { 1: 45.5 } } )

feat = next(layer.getFeatures())
feat.setGeometry(QgsGeometry.fromWkt('Point (-122.4 45.32)'))

Writing and Styling Output Layers

Process data or execute geoprocessing workflows, then write results to temporary scratch layers or permanent outputs:

output_layer = QgsVectorLayer('Point?crs=epsg:4326',
prov = output_layer.dataProvider()

feat = QgsFeature()
feat.setGeometry(QgsGeometry.fromWkt('Point(-117 33)'))

symbol = QgsMarkerSymbol.createSimple({'color': 'green'})


Debugging Import Issues

Techniques for Checking and Validating PYTHONPATH

Import errors still happening? Double check PYTHONPATH was set up correctly by printing sys.path:

import sys

Evaluate whether the QGIS Python library paths are present.

Finding Missing Libraries and Fixing Broken Paths

If paths referenced in PYTHONPATH are invalid or lack key subdirectories, fix by adjusting to point to proper folder. This may happen after QGIS upgrades or if environment differs from original install. Testing imports by incrementally tweaking paths can identify issues.

Troubleshooting QGIS ‘bin’ Path Problems

Algorithms fail to import despite PYTHONPATH set up correctly? Ensure PATH references the QGIS binary executable folder. Test by printing PATH, or try running qgis_process.exe from the command line.

Next Steps and Additional Resources

Recommendations for More Advanced Scripting

With access now enabled to PyQGIS, explore further possibilities:

  • Building processing workflows by chaining algorithm calls
  • Writing custom Python processing algorithms
  • Using PyQGIS widgets and map tools by integrating QGIS with PyQt

Links to QGIS API Docs and Community Forums

Leave a Reply

Your email address will not be published. Required fields are marked *