[GRASS-dev] r.mapcalc in Python script (parse error)

Glynn Clements glynn at gclements.plus.com
Wed Oct 26 15:30:23 EDT 2011


Margherita Di Leo wrote:

> I need a little help with r.mapcalc syntax in Python script. I want to
> convert the following formula:
> 
> grass.run_command('r.mapcalculator', amap = r_stream+'_nothin' , formula =
> '%s*%s' % (r_stream+'_nothin', r_mask) , outfile = r_stream+'_nothin',
> overwrite = True)
> 
> I want to use r.mapcalc instead of r.mapcalculator. So I write:
> 
> grass.mapcalc("$r_stream_nothin = $r_stream_nothin * $r_mask",
>                       r_mask = r_mask,
>                       r_stream_nothin = r_stream+'_nothin')
> 
> but I get parse error. What's the correct way to do this? The aim is to add
> the suffix '_nothin' to the existing variable name r_stream.

There's nothing obviously wrong with the above code, although you
should probably quote the map names, i.e.:

	grass.mapcalc("'$r_stream_nothin' = '$r_stream_nothin' * '$r_mask'",
	 ...

Map names which contain symbols need to be quoted, otherwise e.g. a
map named "map-name" will be parsed as a subtraction.

Check the values of r_stream and r_mask with e.g.:

	print repr(r_stream), repr(r_mask)

Running 'g.gisenv set=DEBUG=1' prior to the script will enable some
debugging information, including the exact r.mapcalc command.

Also, using the same map as both input and output is unwise. It
appears to work, at least for simple cases, but shouldn't be relied
upon.

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


More information about the grass-dev mailing list