Calling processing tools from Python

See QGIS documentation for details.

QGIS processing is available in Python through processing module. On line 3 we will loop over all available algorithms. By a simple condition on line 4 only tools containing a word “buffer” in the name will be printed out.

1from qgis import processing
2
3for alg in QgsApplication.processingRegistry().algorithms():
4    if 'buffer' in alg.id():
5        print(alg.id(), "->", alg.displayName())

List parameters for selected algorithm:

1    if alg.id() == 'native:buffer':
2        for p in alg.parameterDefinitions():
3            print(p.name(), p.description())

Let’s select native:buffer tool and execute it by Python code.

 1from qgis import processing
 2
 3output = '/tmp/pozarni_stanice_10km.shp'
 4processing.run("native:buffer", {
 5    'INPUT': '/home/martin/geodata/gismentors/qgis-data/shp/osm/pozarni_stanice.shp',
 6    'DISTANCE': 10000,
 7    'SEGMENTS': 10,
 8    'DISSOLVE': True,
 9    'OUTPUT': output
10})

Newly created layer can be added into layer tree (see next section for PyQGIS introduction):

1layer = QgsVectorLayer(output, os.path.basename(output), 'ogr')
2QgsProject.instance().addMapLayer(layer)