4

How can I run a custom algorithm using processing.run ?

I've extended a QgsProcessingAlgorithm following qgis docs.

I've managed to run a native algorithm in a standalone PyQGIS script following Using QGIS3 Processing algorithms from standalone PyQGIS scripts (outside of GUI)

QgsApplication.processingRegistry().algorithms() does not show my algorithm.

Germán Carrillo
  • 36,307
  • 5
  • 123
  • 178
Dorin
  • 143
  • 6

1 Answers1

6

Based on Using QGIS3 Processing algorithms from standalone PyQGIS scripts (outside of GUI), you need at least 2 new files:

  1. An algorithm provider (example_algorithm_provider.py, see sample provider), which helps you register your algorithm, and
  2. Your Processing algorithm (example_processing_algorithm.py, see sample algorithm), where you define the algorithm logic.

The PyQGIS standalone script would be like this:

import sys
from qgis.core import (
     QgsApplication, 
     QgsVectorLayer
)

See https://gis.stackexchange.com/a/155852/4972 for details about the prefix

QgsApplication.setPrefixPath('/docs/dev/qgis/core/QGIS/build_master/output', True) qgs = QgsApplication([], False) qgs.initQgis()

Append the path where processing plugin can be found

sys.path.append('/docs/dev/qgis/core/QGIS/build_master/output/python/plugins')

import processing from processing.core.Processing import Processing Processing.initialize()

Add our own algorithm provider

from example_algorithm_provider import ExampleAlgorithmProvider provider = ExampleAlgorithmProvider() QgsApplication.processingRegistry().addProvider(provider)

Run our custom algorithm

layer = QgsVectorLayer("/docs/geodata/bogota/ideca/Loca.shp", "layer", "ogr") params = {'INPUT': layer} print("RESULT:", processing.run("my_provider:my_algorithm", params)['OUTPUT'])


Notes:

  1. After initializing Processing, we add our own algorithm provider using QgsApplication.processingRegistry().addProvider(provider).
  2. You can see a full example (i.e., this PyQGIS standalone script, the example_algorithm_provider.py and the example_processing_algorithm.py) at this GitHub repo: https://github.com/gacarrillor/pyqgis_scripts/tree/master/pyqgis_custom_processing_algorithm_standalone
Germán Carrillo
  • 36,307
  • 5
  • 123
  • 178