[GRASS-dev] Python equivalent of piping results from one function to another
Pietro
peter.zamb at gmail.com
Sun Oct 18 22:12:59 PDT 2015
Dear Paulo,
On Sun, Oct 18, 2015 at 8:03 PM, Paulo van Breugel
<p.vanbreugel at gmail.com> wrote:
> What would be the python equivalent of:
>
> r.category mymap | r.category mymap rules=-
Let's split the problem in two step.
First capture the output of a module (the python equivalent of bash pipe):
{{{
>>> from subprocess import PIPE # from the standard library import PIPE costant
>>> from grass.pygrass.modules import Module # import the Module class from pygrass
>>> rcat = Module('r.category', 'landuse', stdout_=PIPE) # use the spacial parameter stdout_
>>> rcat.outputs.stdout # the stdout is an attribute of the instanced class
'1\tdeveloped\n2\tagriculture\n3\therbaceous\n4\tshrubland\n5\tforest\n6\twater\n7\tsediment\n'
>>> print(rcat.outputs.stdout)
1 developed
2 agriculture
3 herbaceous
4 shrubland
5 forest
6 water
7 sediment
}}}
Second provide a string as 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')
}}}
or to do both things in one line:
{{{
Module('r.category', 'mymap', rules='-', stdin_=Module('r.category',
'landuse', stdout_=PIPE).outputs.stdout)
}}}
You can use a shourtcut to have a cleaner syntax close to bash:
{{{
>>> from grass.pygrass.modules.shortcuts import raster as r
>>> r.category('mymap', rules='-', stdin_=r.category('landuse', stdout_=PIPE).outputs.stdout)
Module('r.category')
}}}
There is an example in the documentation using r.colors but it is not
rendered corectly [0]
Have fun!
Pietro
[0] https://grass.osgeo.org/grass71/manuals/libpython/pygrass.modules.interface.html#pygrass.modules.interface.module.Module
More information about the grass-dev
mailing list