[GRASS-user] Parsing output with python
Glynn Clements
glynn at gclements.plus.com
Wed Apr 7 19:38:46 EDT 2010
thedok78 wrote:
> I am porting a bash script to python and for it I need to know the number of
> cells of a certain category. Right now I use this syntax:
> grass.parse_command('r.stats',flags='c',input='map'), but the output is
> something like this: {'112 525': None.. }.
> Is there a way to have {'112':525..} so that I can easy get the number of
> cells ?
You need to use sep=' ' (the default separator is a colon).
But ideally you shouldn't use parse_command for programs which can
return a lot of output; use pipe_command() and parse the output
yourself, e.g.:
p = grass.pipe_command('r.stats',flags='c',input='map')
result = {}
for line in p.stdout:
[val,count] = line.strip().split()
result[int(val)] = int(count)
p.wait()
Also, parse_command() will use strings as keys and values, when
integers would probably be more useful.
--
Glynn Clements <glynn at gclements.plus.com>
More information about the grass-user
mailing list