PyGRASS equivalent of piping results from one function to another

Author: Paulo van Breugel
Last updated on: October 26, 2015


When using GRASS commands on the command line, one very neat little trick is to ‘pipe’ results from one function directly to another. An example I used in an earlier post is:

r.category My_map | r.category My_map rules=-

So, how does that work in python using pygrass? I got a great answer with clear examples from Pietro on the GRASS GIS developers email list, which I am copying below. The problem can be split in two components (before and after the pipe).

First component

The first component is to capture the output of a module (the python equivalent of bash pipe):

# from the standard library import PIPE costant
from subprocess import PIPE
# import the Module class from pygrass 
from grass.pygrass.modules import Module 
# Now run the r.category module. The important part
# here is to use the special parameter stdout_
rcat = Module('r.category', 'landuse', stdout_=PIPE)
# the stdout is an attribute of the instanced 
# class rcat
# You can also use the print command
1       developed
2       agriculture
3       herbaceous
4       shrubland
5       forest
6       water
7       sediment

Second component

The second component is to provide the output as string to the stdinput of a module.

Module('r.category', 'mymap', rules='-',

Combining the two

And now we need to combine the two, similar how the pipe symbol on the command line combines two commands.

Module('r.category', 'mymap', rules='-',
       stdin_=Module('r.category', 'landuse',

Easy and effective, just how it should be :-). See here for more information and examples.


Software: @grassgis
Tools: @pygrass
Subject: @pipe