[GRASS-user] GRASS-Python Script: Check if output already exists, overwrite
Glynn Clements
glynn at gclements.plus.com
Thu Apr 11 04:00:27 PDT 2013
Johannes Radinger wrote:
> I would like to check if the file defined as output in a python script
> already exists and fire an error when it exists and the overwrite flag is
> not set. Furhtermore I'd like
> to check this already in the beginning before all calculations in the
> script are executed.
g.parser should do this automatically.
If an option has "new" in the gisprompt field, G_parser() checks that
either the file/map/etc doesn't exist or overwrite is enabled.
The only time you should need to do this manually is if an output name
isn't simply an option value (e.g. r.mapcalc's output maps are
specified in the expression, r.rgb takes an output "template" to which
it appends a .r/.g/.b suffix, etc).
> I thought about something like:
>
> output = options['output']
> if (grass.find_file(name = output, element = 'cell')['file'] and
> grass.read_command("g.gisenv", get = "GRASS_OVERWRITE")!=1):
> grass.fatal(_("Output file exists already, either change output
> name or set overwrite-flag"))
>
> but what is the correct way to get the information if the overwrite flag is
> set
> or not for that script? The GRASS-OVERWRITE variable is not set although
> the script is launched with --overwrite. So how to get this info?
The grass.script.overwrite() function returns True if overwrite is
enabled. Also, os.environ['GRASS_OVERWRITE'] will have been set to '1'
by grass.script.parser() so that the overwrite status propagates down
to any commands executed by the script.
--
Glynn Clements <glynn at gclements.plus.com>
More information about the grass-user
mailing list