Introduction to the GRASS GIS 7 Python Scripting Library

The GRASS GIS 7 Python Scripting Library provides functions to call GRASS modules within scripts as subprocesses. The most often used functions include:

  • run_command: most often used with modules which output raster/vector data where text output is not expected
  • read_command: used when we are interested in text output
  • parse_command: used with modules producing text output as key=value pair
  • write_command: for modules expecting text input from either standard input or file

Besides, this library provides several wrapper functions for often called modules.

Calling GRASS GIS modules

We start by importing GRASS GIS Python Scripting Library:


In [ ]:
import grass.script as gscript

Before running any GRASS raster modules, you need to set the computational region using g.region. In this example, we set the computational extent and resolution to the raster layer elevation.


In [ ]:
gscript.run_command('g.region', raster='elevation')

The run_command() function is the most commonly used one. Here, we apply the focal operation average (r.neighbors) to smooth the elevation raster layer. Note that the syntax is similar to bash syntax, just the flags are specified in a parameter.


In [ ]:
gscript.run_command('r.neighbors', input='elevation', output='elev_smoothed', method='average', flags='c')

Specifics of interactive interpreters

When using the GUI, we can look at the map right away. In scripts, we rarely render a map. In IPython Notebook we are able to show a map as a result. For this we use function view() from a custom Python module render supplied with these notebooks. (This function might be part of GRASS GIS Python API for IPython in the future.)


In [ ]:
from render import view
view(rasters=['elev_smoothed'])

To simplify the re-running of examples, we set the environmental variable GRASS_OVERWRITE, which allows direct overwriting of results from previous runs, bypassing the overwrite checks.


In [ ]:
import os
os.environ['GRASS_OVERWRITE'] = '1'

When an unrecoverable error occurs (due to incorrect parameter use or other issues), the GRASS GIS functions usually print the error message and end the program execution (by calling the exit() function). However, when working in an interactive environment such as IPython, the behavior can be changed using set_raise_on_error() function. The following call will cause GRASS GIS Python functions to raise an exception instead of calling exit().


In [ ]:
gscript.set_raise_on_error(True)

Calling GRASS GIS modules with textual input or output

Textual output from modules can be captured using the read_command() function.


In [ ]:
print(gscript.read_command('g.region', flags='p'))

In [ ]:
print(gscript.read_command('r.univar', map='elev_smoothed', flags='g'))

Certain modules can produce output in key-value format which is enabled by the g flag. The parse_command() function automatically parses this output and returns a dictionary. In this example, we call g.proj to display the projection parameters of the actual location.


In [ ]:
gscript.parse_command('g.proj', flags='g')

For comparison, below is the same example, but using the read_command() function.


In [ ]:
print(gscript.read_command('g.proj', flags='g'))

Certain modules require the text input be in a file or provided as standard input. Using the write_command() function we can conveniently pass the string to the module. Here, we are creating a new vector with one point with v.in.ascii. Note that stdin parameter is not used as a module parameter, but its content is passed as standard input to the subprocess.


In [ ]:
gscript.write_command('v.in.ascii', input='-', stdin='%s|%s' % (635818.8, 221342.4), output='view_point')

Convenient wrapper functions

Some modules have wrapper functions to simplify frequent tasks.

We can obtain the information about the vector layer which we just created with the v.info wrapper.


In [ ]:
gscript.vector_info('view_point')

It is also possible to retrieve the raster layer history (r.support) and layer information (r.info) or to query (r.what) raster layer pixel values.


In [ ]:
gscript.raster_what('elevation', [[635818.8, 221342.4], [635710, 221330]])

As another example, the r.mapcalc wrapper for raster algebra allows using a long expressions.


In [ ]:
gscript.mapcalc("elev_strip = if(elevation > 100 && elevation < 125, elevation, null())")
print(gscript.read_command('r.univar', map='elev_strip', flags='g'))

The g.region wrapper is a convenient way to retrieve the current region settings (i.e., computational region). It returns a dictionary with values converted to appropriate types (floats and ints).


In [ ]:
region = gscript.region()
print region
# cell area in map units (in projected Locations)
region['nsres'] * region['ewres']

We can list data stored in a GRASS GIS location with g.list wrappers. With this function, the map layers are grouped by mapsets (in this example, raster layers):


In [ ]:
gscript.list_grouped(['raster'])

Here is an example of a different g.list wrapper which structures the output as list of pairs (name, mapset). We obtain current mapset with g.gisenv wrapper.


In [ ]:
current_mapset = gscript.gisenv()['MAPSET']
gscript.list_pairs('raster', mapset=current_mapset)

Exercise

Derive a new slope layer from the raster layer elevation using r.slope.aspect. Then calculate and report the slope average and median values (hint: see r.univar).


In [ ]:

Export all raster layers from your mapset with a name prefix "elev_*" as GeoTiff (see r.out.gdal). Don't forget to set the current region for each map in order to match the individual exported raster layer extents and resolutions since they may differ from each other.


In [ ]: