source: nappy/trunk/nappy/utils/parse_config.py @ 3406

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/nappy/trunk/nappy/utils/parse_config.py@3406
Revision 3406, 1.3 KB checked in by astephen, 12 years ago (diff)

Tested some of this with working functions.

RevLine 
[3321]1"""
2parse_config.py
3===================
4
5Parses config file for nappy.
6
7"""
8
9# Standard library imports
10import ConfigParser
11import os
12
13# Global variables
[3387]14base_dir = os.environ.get("NAPPY_BASE_DIR", ".." + os.path.sep + "..")
[3379]15config_file = os.path.join(base_dir, "nappy.ini")
[3324]16config_dict = None
[3321]17
[3324]18class MyCasePreservingConfigParser(ConfigParser.ConfigParser):
19    optionxform = str
[3321]20
21def makeConfigDict(cf=config_file):
22    """
23    Parses config file and returns dictionary of sub-dictionaries
24    for each section holding Keyword-Value pairs.
25    """
26    d = {}
[3324]27    conf = MyCasePreservingConfigParser()
[3321]28    conf.read(cf)
29
[3406]30    # get all sections and content
[3321]31    for section in conf.sections():
32        d[section] = {}
[3324]33        for item in conf.options(section):
34            value = conf.get(section, item)
35            if item.find("&") > -1:
36                item = tuple(item.split("&"))
37            if value.find("&") > -1:
38                value = tuple(value.split("&"))
39            d[section][item] = value
[3321]40
41    return d
42
43
44def getConfigDict(cf=config_file):
45    "Checks if already made and only makes if required."
[3324]46    global config_dict
47    if config_dict == None:
48        config_dict = makeConfigDict(cf)
49    return config_dict
[3321]50
51
52if __name__=="__main__":
53    print getConfigDict()
Note: See TracBrowser for help on using the repository browser.