Based on Using QGIS3 Processing algorithms from standalone PyQGIS scripts (outside of GUI), you need at least 2 new files:
- An algorithm provider (
example_algorithm_provider.py
, see sample provider), which helps you register your algorithm, and
- 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:
- After initializing Processing, we add our own algorithm provider using
QgsApplication.processingRegistry().addProvider(provider)
.
- 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