[GRASS-dev] How to use a rules file in add-on script without hardcoding the path

Hi all,

I'm fairly new to GRASS, so I apologise if this is a silly question - but I couldn't find the answer anywhere in either the User or Developer Wikis. I have written a (very simple) Python add-on which uses the r.reclass tool. Of course, to use this tool I need to provide a file with the reclass details in it. I am currently having issues getting GRASS to find this file when I run the script and I would like it to do this without hard-coding the script path - ie. by using relative paths. I have two questions:

1. If I am running this script from somewhere outside of the GRASS scripts directory (eg. from somewhere in my home directory), how should I write my script so that it simply uses the reclass file in the same directory as the script? Currently my script contains the line:

grass.run_command("r.reclass", input = options['input'], output = options['output'], rules = "./zerotonull.rules")

where zerotonull.rules is the file that contains the declass rules, but this always gives an error saying it can't find that file.

2. If I want to distribute this script (either just to friends/colleagues or by adding it to the GRASS add-on repository), how should I set up my Makefile so that the reclass rules file gets put in the right place, and the script can then find it?

I hope this is the right place to ask this - if not, please accept my apologies.

Best regards,

Robin

Robin Wilson wrote:

1. If I am running this script from somewhere outside of the GRASS
scripts directory (eg. from somewhere in my home directory), how
should I write my script so that it simply uses the reclass file in
the same directory as the script? Currently my script contains the
line:

grass.run_command("r.reclass", input = options['input'], output = options['output'], rules = "./zerotonull.rules")

where zerotonull.rules is the file that contains the declass rules,
but this always gives an error saying it can't find that file.

You can't assume that the directory containing the script is the
current directory. However, sys.path[0] is usually the directory
containing the script.

2. If I want to distribute this script (either just to
friends/colleagues or by adding it to the GRASS add-on repository),
how should I set up my Makefile so that the reclass rules file gets
put in the right place, and the script can then find it?

If the rules file is generated within the script, use Python's
tempfile module to select an appropriate location.

If the rules file is static data, it's probably simplest to embed the
data within the script as a raw string literal and feed it to
r.reclass via stdin, e.g. using grass.write_command().

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