[GRASS-dev] Python Scripting

Glynn Clements glynn at gclements.plus.com
Thu Jul 17 02:53:59 EDT 2008


Michael Barton wrote:

> This seems very handy for a lot of basic GRASS scipting, including  
> replacing bash scripts with Python ones--something that I'd like to  
> start on soon

Before we start, we need to figure out a suitable template for Python
scripts. I've recently fixed some bugs in the g.parser/test.py
example, but I've just discovered another issue:

g.parser needs to both open the script as a text file (to parse the
option definitions), and to execute it. For the former, the script
needs to be able to obtain its own absolute path.

However; the Python documentation for sys.argv says:

	The list of command line arguments passed to a Python script. 
	argv[0] is the script name (it is operating system dependent
	whether this is a full pathname or not).

If it isn't a full path, sys.path[0] should be the directory
containing the script. So, the code which invokes g.parser needs to
force argv[0] to an absolute path before passing it to g.parser.

Even more fundamentally, we should question whether the existing
g.parser interface is the right way to go for Python. I'm thinking
that it would be better to give g.parser an option to write the
option/value pairs to stdout as a Python dictionary, e.g.:

	output = Popen(["g.parser"] + sys.argv, stdout=PIPE).communicate()[0]
	options = eval(output)

[The Popen(..., stdout=PIPE).communicate()[0] idiom is equivalent to
shell backticks; it returns a string containing the data written to
stdout.]

Actually; we probably want some error handling, e.g.:

	child = Popen(["g.parser"] + sys.argv, stdout=PIPE)
	output = child.communicate()[0]
	if child.returncode != 0:
	    raise OSError("Error executing g.parser")
	options = eval(output)

Rather than having to put this in every script, we should provide a
module for it, and have the GRASS startup set PYTHONPATH.

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



More information about the grass-dev mailing list