[GRASS-user] Define Global Variables and use them in a Python script

Glynn Clements glynn at gclements.plus.com
Mon Jul 5 16:43:01 EDT 2010


Kim Besson wrote:

> I've been testing and "kind of " using GRASS-Python scripts for nearly 2
> weeks and it's being great. So far no major issues but now I need to do
> something:
> - From a text file (ASCII) I need to read a few variables and make them
> global bariables I mean, be available and defined for a huge set of Scripts
> in order to avoid to define those variables in each Script. And, in case I
> change them, I only have to change in that ASCII File. My questions are:
> 1- How can I do GRASS to read an external File in order to define GLOBAL
> VARIABLES?
> 2- How can I call them from a GRASS_SCRIPT?

A "global" variable in Python is local to the module in which it's
defined. So you you have a module named config, to access any global
variables in that module from other modules you would need either
"import config" (in which case, variables will be accessible as
config.whatever) or "from config import *" (but as the program grows,
the chances of name collisions increase).

For a set of related variables, e.g. configuration parameters, it's
usually better to make them all members of a specific object, e.g.:

	class Params(object):
	    def __init__(self, filename):
	        # initialise members from file

	# read the config file
	params = Params("config.cfg")

Then you only need to import a single name:

	from config import params

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


More information about the grass-user mailing list