Unit 14 - PyGRASS scripting

PyGRASS also allows calling existing GRASS module similarly as GRASS Scripting Library does (see Unit 11 - Scripting and Unit 12 - Script tuning). The module caller is represented by Module class. In contrast to GRASS Scripting Library which defines several routines to run module (core.run_command, core.read_command, or core.feed_command) in PyGRASS there is only one caller technique.

We can rewrite our simple script created in Unit 12 - Script tuning using PyGRASS.

We start replacing all core.run_command by Module caller, see example below.

from grass.script import run_command

run_command("v.overlay",
             overwrite = True,
             ainput = options["region"],
             binput = options["clouds"],
             operator = "not",
             output = region_mask)

by

from grass.pygrass.modules import Module

Module("v.overlay",
       overwrite = True,
       ainput = options["region"],
       binput = options["clouds"],
       operator = "not",
       output = region_mask)

Then let’s replace core.feed_command. In this case PyGRASS leads to more compact syntax, see below.

   p1 = feed_command("r.recode",
                     overwrite = True,
                     input = "ndvi",
                     output = "ndvi_class",
                     rules = "-")
   p1.stdin.write("""-1:0.1:1
0.1:0.5:2
0.5:1:3""")
   p1.stdin.close()
   p1.wait()

In PyGRASS syntax replaced also by Module class.

   recode_str="""-1:0.1:1
0.1:0.5:2
0.5:1:3"""

   Module("r.recode",
          overwrite = True,
          input = "ndvi",
          output = "ndvi_class",
          rules = "-",
          stdin_ = recode_str)

In similar way also core.read_command can be replaced by Module class, see a code block below.

ret = read_command('v.report', map=options["output"], option='area')
for line in ret.splitlines()[1:]:
    ...

Changed to

ret = Module('v.report', map=options["output"], option='area',
             stdout_=PIPE)
for line in ret.outputs.stdout.splitlines()[1:]:
    ...

Note

In PyGRASS, multiple options need to turned into a list. See example below for v.rast.stats and method option.

Module('v.rast.stats', flags='c', map=options["output"], raster='ndvi',
column_prefix='ndvi', method='minimum,maximum,average')

Changed to

Module('v.rast.stats', flags='c', map=options["output"], raster='ndvi',
column_prefix='ndvi', method=['minimum','maximum','average'])

Sample script to download: ndvi-v4.py

For GRASS scripting the user can choose between two different GRASS Python libraries, or approaches if you want. Either GRASS Scripting Library based on procedural programming techniques or PyGRASS as an objected-oriented approach. It’s your choice. We, in the next units, will focus mainly on PyGRASS.