[GRASS-dev] Parsing output of r.category which includes labels

Nikos Alexandris nik at nikosalexandris.net
Mon Aug 20 17:02:24 PDT 2018

* Moritz Lennert <mlennert at club.worldonline.be> [2018-08-20 13:40:36 +0200]:

>On 19/08/18 22:19, Nikos Alexandris wrote:
>>If I am not wrong, all use cases of `read_command()` [0, 1],
>>in (at least) the grass-addons repository, do not consider an output
>>from `r.category` which includes labels.
>>[0] https://grass.osgeo.org/grass74/manuals/libpython/script.html?highlight=read_command#script.core.read_command
>>[1] https://grass.osgeo.org/grass75/manuals/libpython/script.html?highlight=read_command#script.core.read_command
>>I work on such a case where category numbers come along with label strings.
>>To read category numbers, I came up with:
>>import grass.script as grass
>>grass.read_command('r.category', map=base).split('\n')[:-1]
>>for category in categories:
>>         category = category.split('\t')[0]
>>Is there any other command that will do this better? Would you consider
>>adding one?
>If all the modules are trying to do is get a list of category values, 
>your approach seems the right one to me, but a simple list 
>comprehension should do the trick in one line:
>cats = [int(x[0]) for x in [x.split('\t') for x in 
>g.read_command('r.category', map='RasterMap').splitlines()]]

Great. I love comprehensions (and generators).
It's one of my favourite Python exercises.

>This will work whether there are labels or not. IMHO, there is no need 
>to use anything more sophisticated.
>Especially since a
>grep -R "r.category" * | grep read_command
>only gives 4 hits:
>imagery/i.segment.uspo/i.segment.uspo.py:            numsegments = 
>raster/r.geomorphon/testsuite/test_r_geom.py:        category = 
>read_command('r.category', map=self.outele)
>raster/r.geomorphon/testsuite/test_r_geom.py:        category = 
>read_command('r.category', map=self.outsint)
>raster/r.neighborhoodmatrix/r.neighborhoodmatrix.py:    numneighbors = 
>The first and last only read the length (number) of categories, so 
>this isn't an issue.
>Have you met other instances ?

No.  Yet, my Skepsis now is the following:

The argument you present, if I understand it right, is
"no need to bother", since there aren't but a few potential use cases.

What about better integration and more joyful scripting? `r.category`
handles both values and labels.  And there is currently no
`grass.script` helper function that considers both labels out of the

For example, a parser helper that will return a dictionary.
Is this "too much" here?

Thanks Moritz,
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 228 bytes
Desc: not available
URL: <http://lists.osgeo.org/pipermail/grass-dev/attachments/20180821/68e42da8/attachment.sig>

More information about the grass-dev mailing list