PyGRASS equivalent of piping results from one function to another

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 works 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
rcat.outputs.stdout

'1\tdeveloped\n2\tagriculture\n3\therbaceous\n4\tshrubland\n5\tforest\n6\twater\n7\tsediment\n'

# You can also use the print command
print(rcat.outputs.stdout)

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='-', stdin_='1\tdeveloped\n2\tagriculture\n3\therbaceous\n4\tshrubland\n5\tforest\n6\twater\n7\tsediment\n')
Module('r.category')
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', stdout_=PIPE).outputs.stdout)

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

Advertisements

One thought on “PyGRASS equivalent of piping results from one function to another

  1. Pingback: PyGRASS equivalent of piping results from one function to another | GeoNe.ws

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s