QGIS Python

QGIS is a powerful programming application, that allows you to extend the core functionality of the software, as well as write scripts to automate your tasks.

QGIS 0.9 was the first support Python scripting language. There are several ways to use Python in QGIS Desktop:

  • Create and use plugins
  • Issue commands in the Python console
  • Automatically run Python code when Q-GIS starts
  • Create processing algorithms
  • Create functions for expressions in QGIS
  • Create custom applications based on the QGIS API

Use the Python API to let the user interact with its objects, like; layers, feature or interface.

Main Tools in QGIS for Python

ToolDescription
Python ConsoleBuilt-in terminal for writing Python commands directly
PyQGIS APIPython API to interact with objects (layers, maps, geometries, etc.)
Processing ToolboxRun and script geoprocessing tools using Python
PluginsCreate or use Python-based plugins

QGIS Python Console

The Python console main features are:

  • Python
  • PyQGIS
  • PyQt4
  • QScintilla2
  • osgeo-gdal-ogr

Open Console

To open the console, go to Plugins > Python Console

Console Toolbar

  1. Clear console
  2. Import class
  3. Run command
  4. Show editor
  5. Options
  6. Help

Console Setting

You are already open Python Console panel, click Options tab.

Now the Python Console Setting window appear, show three options is available:

  • Console
  • Editor
  • API

Examples

1. Load a shapefile:

iface.addVectorLayer('/path/to/file.shp', 'My Layer', 'ogr')

1. Create a buffer:

import processing
processing.run("native:buffer", {
    'INPUT': 'my_layer',
    'DISTANCE': 1000,
    'OUTPUT': 'memory:buffered'
})

1. Save a layer to GeoPackage:

QgsVectorFileWriter.writeAsVectorFormat(layer, '/path/out.gpkg', 'UTF-8', layer.crs(), 'GPKG')

1. Print all layer names:

for layer in QgsProject.instance().mapLayers().values():
    print(layer.name())

PyQGIS Developer Cookbook

Scripting in the Python Console

Python API Documentation

Q-GIS Python API documentation project

Scroll to Top