[GRASS-user] Python Script for changing raster values

Glynn Clements glynn at gclements.plus.com
Tue Sep 7 13:51:28 EDT 2010


Christian Schwartze wrote:

> Following code could be one approach:
> 
> os.system("cat %s | r.recode input=map_a output=map_recl" % path_to_rules)
> 
> where path_to_rules is a previously created (temp) file containg the
> reclassifiying rules as for example:

os.system() shouldn't be used. E.g. the above will fail if
path_to_rules contains spaces (as is often the case on Windows).

The preferred approach for the above command is:

	grass.run_command("r.recode", input="map_a",
	    output="map_recl", rules = path_to_rules)

If you have a command which requires input via stdin (rather from a
named file), use e.g.:

	rules_f = open(path_to_rules, "r")
	try:
	    grass.run_command("r.recode", input="map_a",
	        output="map_recl", stdin = rules_f)
	finally:
	    rules_f.close()

Or, if you can rely upon Python 2.5 or later, use:

	from __future__ import with_statement
	with open(path_to_rules, "r") as rules_f:
	    grass.run_command("r.recode", input="map_a",
	        output="map_recl", stdin = rules_f)

Also, even in shell scripts "cat file | command" is suboptimal; use
"command < file" instead.

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


More information about the grass-user mailing list