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

Kim Besson kimbesson1981 at gmail.com
Tue Jul 6 12:07:12 EDT 2010


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?
Kim



2010/7/5 Glynn Clements <glynn at gclements.plus.com>

>
> 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>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.osgeo.org/pipermail/grass-user/attachments/20100706/9a4e1fd1/attachment.html


More information about the grass-user mailing list