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).
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
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.
If you have questions
If you have questions or comments about the text, let me know. You can use this contact form. Please make sure to include the page title ("PyGRASS equivalent of piping results from one function to another") or page name ("pygrass-equivalent-of-piping").