[GRASS-user] Parsing output with python

Hello everybody,
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 ?

Thank you very much
Luca
--
View this message in context: http://n2.nabble.com/Parsing-output-with-python-tp4864105p4864105.html
Sent from the Grass - Users mailing list archive at Nabble.com.

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@gclements.plus.com>

Thank you very much, it worked fine!

Ciao
Luca
--
View this message in context: http://n2.nabble.com/Parsing-output-with-python-tp4864622p4870862.html
Sent from the Grass - Users mailing list archive at Nabble.com.