Skip to content

Instantly share code, notes, and snippets.

@pmav99
Last active June 19, 2019 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmav99/6ca58c8c0bdcb61903de643909147fae to your computer and use it in GitHub Desktop.
Save pmav99/6ca58c8c0bdcb61903de643909147fae to your computer and use it in GitHub Desktop.
QGIS 3 + Processing + Python API example
import os
import pathlib
import sys
import typing
# The exact values of these paths depend on your QGIS installation
QGIS_ROOT = pathlib.Path("/opt/qgis-git")
QGIS_PATH = QGIS_ROOT / "share/qgis/python"
QGIS_PLUGIN_PATH = QGIS_PATH / "plugins"
# Add qgis to the PATH
sys.path.insert(1, QGIS_PATH.as_posix())
sys.path.insert(2, QGIS_PLUGIN_PATH.as_posix())
# We can now import QGIS modules
import qgis.core
import qgis.gui
import processing
# Initialize QGIS application
qgis.core.QgsApplication.setPrefixPath(QGIS_ROOT.as_posix(), True)
app = qgis.core.QgsApplication(
[], False
) # setting the second argument to False disables the GUI
app.initQgis()
# Initialize processing
from processing.core.Processing import Processing
Processing.initialize()
def get_raster_layer(
path: typing.Union[str, pathlib.Path], name: str
) -> qgis.core.QgsRasterLayer:
path = pathlib.Path(path).expanduser().resolve()
layer = qgis.core.QgsRasterLayer(path.as_posix(), name)
if not layer.isValid():
raise ValueError(f"Could not load layer: {path} - {name}")
return layer
# get a raster layer
b1 = get_raster_layer("~/LC08/LC80440342016259LGN00_B1.TIF", "b1")
# Run r.univar the raster layer
out_file = pathlib.Path("/tmp/out.txt")
r_univar_parameters = {"map": b1, "output": out_file.as_posix()}
result = processing.run("grass7:r.univar", parameters=r_univar_parameters)
# show output
print(result)
print(out_file.read_text())
app.exitQgis()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment