3

I want to write a python script to get and save basin area value of interested points on a drainage line from outside GRASS. I think the workflow could be:

  1. run r.watershed and get drainage file
  2. run r.water.outlet to get drainage area file of interested points
  3. run r.stats to get area value of each interested point and save them in a CSV file

The python script for the first 2 stages ran well, and thus I wrote a python script r_stats trying to run GRASS GIS module r.stats from outside,

import os
import sys
from GRASSGIS_conn import GRASSGIS_conn


def r_stats(flag, map_name, sep):

    g.run_command('r.stats', flags = flag, input = map_name, separator = sep, output = 'dd.csv')


if __name__ == "__main__":


    sys.path.append(os.path.join(os.environ['GISBASE'], 'etc', 'python'))
    import grass.script as g
    gisdb = 'C:\Users\Heinz\Documents\grassdata'
    location = 'nl'
    mapset = 'nl'
    GRASSGIS_conn(gisdb, location, mapset)
    map_name = 'b1'
    flag = 'na'
    sep = 'comma'
    r_stats(flag, map_name, sep)

The resulting CSV file contains a category column and another area value column although I just want area value. Now the problem is that because I need to get area values of more than one raster files loaded in GRASS GIS, and the code above would output too many CSV files and it's inefficient to re-organize them.

Is there a way to store these area value in a numpy array? Or are there better way to get and save area value than r.stats?

3

grass.read_command (g.read_command('r.stats'...) instead of g.run_command('r.stats' ...)) grass.read_command "reads the data from the command's stdout, and returns it as a string" See: https://grasswiki.osgeo.org/wiki/GRASS_Python_Scripting_Library#Uses_for_read.2C_feed_and_pipe.2C_start_and_exec_commands

2

I edited my code based on @Stefan B.'s idea:

def r_stats(flag, map_name, sep):

    res = g.read_command('r.stats', flags = flag, input = map_name, separator = sep)
    nres = numpy.array(float(res[2:]))
    print nres

it outputs just area value in numpy array form.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.