Running Native Qgis Algorithms From Standalone Pyqgis Scripts

Why Run Algorithms from Scripts?

Executing QGIS geoprocessing and spatial analysis tools from Python scripts instead of the graphical user interface offers several advantages:

  • Automation and reproducibility – Scripting workflows allows them to be easily repeated and shared
  • Custom workflows and analysis – Flexibly chain together sequences of tools that would be difficult to do manually
  • Headless processing without GUI – Run workflows on servers or clusters where installing QGIS is not feasible

Accessing Native QGIS Algorithms

To leverage the hundreds of geospatial algorithms included in QGIS from a Python script, the Processing library must be imported:


import processing
from qgis.core import *

This provides access to the same tools available in the QGIS Toolbox and Graphical Modeler. Review the algorithms by printing them:


for alg in QgsApplication.processingRegistry().algorithms():
    print(alg.id(), "->", alg.displayName())

Running Algorithms

Algorithms can be executed by creating the needed input Parameter objects and passing them to the Processing.run() function. Results are stored for additional analysis.


params = {
  'INPUT': 'roads.gml',
  'LENGTH': 100, 
  'OUTPUT': 'selected_roads.shp'
}
results = processing.run("native:filterbylength", params)
print(results) 

Processing Vector Data

Many useful geoprocessing functions are available for manipulating vector data:

  • Geoprocessing tools – Clip, buffer, simplify, reshape geometries
  • Geometry operations – Calculate areas, lengths, centroids, bounding boxes
  • Field calculations – Update, compute new, or join attributes

# Simplify road network to remove minor irregularities  
params = {
  'INPUT': roads_layer,
  'DISTANCE': 5,
  'OUTPUT': simplified_roads  
}
processing.runAndLoadResults("native:simplifygeometries", params)

Processing Raster Data

Common tasks for working with imagery and gridded datasets include:

  • Manipulating band math – NDVI, image statistics, reclassification
  • Spatial analysis – Slope, aspect, viewshed, distance calculations
  • Terrain analysis – Hillshade, contours, cut and fill volumes

# Classify satellite image using unsupervised k-means clustering
params = {
  'INPUT': satellite_img, 
  'NCLUSTERS': 6,
  'OUTPUT': classified_img
}
processing.run("native:kmeansclustering", params)

Managing Data Sources

Workflows often need to load data layers for input or write out result layers:


# Load a vector layer from a GeoPackage database 
layer = QgsVectorLayer("geopackage.gpkg|layername=roads", "roads")
QgsProject.instance().addMapLayer(layer)

# Write polygonized raster as new vector shapefile
params = {
  'INPUT': raster_layer, 
  'OUTPUT': "polygons.shp" 
}
processing.run("gdal:polygonize", params)

Example Workflows

By connecting together sequences of geoprocessing tools, custom spatial analysis workflows can be created, including:

  • Vector overlay analysis – Intersect, erase, union, join data from multiple shapefiles
  • Satellite image classification – Segment land cover types using band ratios and clustering
  • DEM terrain modeling – Compute slope, aspect, watersheds, and 3D visualizations from elevation models

# Hydrological watershed analysis:

# Load DEM raster layer
dem = iface.addRasterLayer("elevation.tif") 

# Calculate flow direction
fdir = processing.run("native:filledirection", {'INPUT': dem})

# Compute watershed basins
basins = processing.run("native:watershedbasins", {'INPUT': fdir}) 

# Attributes watershed ID to each cell  
params = { 
  'INPUT': basins,
  'RASTER': dem,
  'COLUMN_PREFIX': 'ws',
  'OUTPUT': 'watersheds_dem' 
}
processing.run("qgis:rasterlayerstatistics", params)

Tips for Robust Scripts

Some best practices for creating reusable and reliable scripted analysis workflows include:

  • Handling errors and logging – Wrap tool executions in try/except blocks and write log files
  • Parallel processing – Use threads or subprocesses for operations on large datasets
  • Sharing workflows – Save scripts, models, and custom Python plugins in repositories

import logging
log_file = "process.log"
logging.basicConfig(filename=log_file, level=logging.INFO)

try:
  results = processing.run("algorithm_id", parameters)
  logging.info("Successful execution")
except:
  logging.error("Execution failed")  

Next Steps

Further capabilities for leveraging QGIS in custom Python programming include:

  • Scheduling and integrating – Looping tasks, remote execution via SSH, chaining workflows
  • Python GUI development – Building interfaces and dashboards using PyQt
  • Contributing algorithms – Develop new processing tools using PyQGIS API

By combining the geospatial analysis power of QGIS with the flexibility of Python scripting, the possibilities are endless for automating spatial workflows to serve both geographic research and operational needs.

Leave a Reply

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