[GRASS-dev] Python Scripting

Glynn Clements glynn at gclements.plus.com
Fri Jul 18 02:09:55 EDT 2008


Dan D'Alimonte wrote:

> I'm curious if any though has been given to developing an actual GRASS
> library for Python that goes beyond calling executables with system calls?
> 
> I'm thinking about a model that encapsulates the GRASS environment and
> allows for both low-level processing like the C library, and high-level
> use of existing modules like shell scripts.
> 
> I'll admit I have not given this a lot of though, but a hypothetical,
> and  quickly thought-out, example could be something like:
> 
> 
> 
> from grass import module, layer, cell, parser
> 
> def r_add(inLayers, outLayer):
> 	for outCell in outLayer.cells:
> 		sum = cell(type=outLayer.cellType)
> 		for l in inLayers:
> 			c = l.getCellAtSameLocation(outCell)
> 			if c.value==cell.null:
> 				sum.value = cell.null
> 				break
> 			sum.value += c.value
> 		outCell.value = c.value
> 	outLayer.commit()
> 		
> if __name__ == "__main__":
> 	# Set up module information here
> 	# Set up and run parser
> 	# Open input layers
> 	# Create new layer for output
> 	# call r_add()
> 	# close layers	
> 
> 
> 
> I don't know if this would even be feasible, but I think it would make a 
> nice addition to GRASS's Python support. If done right it would even 
> allow other python-based GRASS modules to be called-on without having to 
> make a system-call (eg. from raster_add import r_add).

Raster processing in Python is likely to be too slow to be practical.

> As to existing modules, what about a helper function to access then?
> 
> module.executeModule( name="r.stats", options={ "input": 
> "elevation.dem,slope,aspect", "fs": ",", "output": "elev.csv"}, 
> flags=["q", "1", "n", "g"] )

This idea has occurred to me. Some comments:

Pass argument values as Python values, e.g. passing multiple values as
lists, passing numeric types directly, etc, and have the interface
convert them to strings. Pass the flags as a single string.

module.execute( "r.stats",
                options = { "input": ["elevation.dem", "slope", "aspect"],
                            "fs": ",",
                            "output": "elev.csv" },
                flags = "q1ng" )

Provide a lower-level function which simply generates the command to
pass to Popen(), for cases where you want to interact with the child
process.

Provide an intermediate function which starts the process, returning
an object from which you can obtain structured progress information:
percentage complete, any messages along with their type (debug, info,
warning), etc.

-- 
Glynn Clements <glynn at gclements.plus.com>


More information about the grass-dev mailing list