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

Glynn Clements glynn at gclements.plus.com
Wed Jul 7 10:10:38 EDT 2010


Kim Besson wrote:

> Hi Glynn and rest of the list
> I have tested this method by creating a config.py and a demo-example of
> config and I'm not being able to use this solution. Maybe I'm not fully
> understanding it (never used classes in Python):
> 1- I create a config1.py file in a working Python directory
> 2- I added this to config.py
> class Params(object):
> def __init__(self, filename):
>       params = Params("config.cfg")
> 3- My config.cfg has the following:
> Ah= '1'
> Bu= '2'
> 
> 4- Just for testing, in a Python Shell I do:
> from config1 import Params
>  (WORK)
> Then:
> >>> print Params
> I get: <class 'config1.Params'>
> So I cannot access variables inside config.cfg
> What am I doing wrong?

First, Params.__init__ needs to actually read the specified file.
E.g.:

-------------- next part --------------
import grass.script as grass

class Params(object):
    def __init__(self, filename):
        f = open(filename, 'r')
        s = f.read()
        f.close()
        self.params = grass.parse_key_val(s)

    def __getattr__(self, name):
        return self.params[name]

    def __getitem__(self, name):
        return self.params[name]

    def __repr__(self):
        return repr(self.params)

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

-------------- next part --------------

This assumes that the config.cfg file uses variable=value syntax.

The resulting config.params object allows the parameters to be
accessed as object attributes (e.g.: config.params.something) or
dictionary entries (e.g.: config.params['something']).

The Python standard library has the ConfigParser module if you want
more complex functionality:

	http://docs.python.org/library/configparser.html

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


More information about the grass-user mailing list