[GRASS-user] Python scripts for the Pareto Boundary, tested using spearfish60 data [How to merge multiple python scripts in one?]

Glynn Clements glynn at gclements.plus.com
Sun Nov 8 03:19:23 EST 2009


Νίκος  	Αλεξανδρής wrote:

>  How is merging/ calling the several scripts in/ from within just one
> script done best? What strategy is best? I really have trouble to get
> this done. 

It's hard to say without understanding likely workflows.

However, if you want to make most of the code into Python modules, one
suggestion is to have the body of the script (the code in the
"if __name__ == '__main__':" block) read the various fields from the
"options" and "flags" variables and pass them to the functions as
parameters, rather than having the functions read global variables
(Python doesn't actually have global variables; "global" variables are
local to a module).

BTW, this is wrong:

            flags = "-o",\

It happens to work at present, but the correct method to pass the
"--o" flag is to use "overwrite = True" (analogous to "quiet = True"
for the "--q" flag and "verbose = True" for the "--v" flag).

If you want to enable these flags throughout the script, you can use:

	os.environ['GRASS_OVERWRITE'] = '1'	# --o
	os.environ['GRASS_VERBOSE'] = '0'	# --q
	os.environ['GRASS_VERBOSE'] = '3'	# --v

In general, it's best to leave these settings to the user. If the user
runs the script with --o, --q, and/or --v, the corresponding
environment variables will be set by grass.parser(). If the user has
those variables set in their environment, the values will be inherited
by the script.

If you want to examine the settings use the overwrite() and/or
verbosity() functions in grass.script.

Also, for writing log messages, string.Template is preferable when
there are multiple substitutions. E.g. rather than:

	print """\n     + Vector grid of size %d rows x %d ( %s cells) columns created"""\
	% (rows, cols, cells)

using:
	print string.Template(
		"""\n     + Vector grid of size ${rows} rows x ${cols} (${cells} cells) columns created"""
		).substitute(rows = rows, cols = cols, cells = cells)

makes it easier to correlate the fields with the values. It also makes
it easier to localise the message, as the fields can be re-ordered if
needed.

If you do a lot of this, consider a utility function, e.g.:

	def log(msg, **kwargs):
		grass.message(string.Template(msg).substitute(**kwargs))

I'm wondering whether grass.message() etc should be extended in this
manner.

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


More information about the grass-user mailing list