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

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

Updates to config parser and test.

Line 
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
14base_dir = os.environ.get("NAPPY_BASE_DIR", ".." + os.path.sep + "..")
15config_file = os.path.join(base_dir, "nappy.ini")
16config_dict = None
17annotations_config_dict = None
18
19
20class MyCasePreservingConfigParser(ConfigParser.ConfigParser):
21    optionxform = str
22
23def makeConfigDict(cf=config_file):
24    """
25    Parses config file and returns dictionary of sub-dictionaries
26    for each section holding Keyword-Value pairs.
27    """
28    d = {}
29    conf = MyCasePreservingConfigParser()
30    conf.read(cf)
31
32    # get all sections and content
33    for section in conf.sections():
34        d[section] = {}
35        for item in conf.options(section):
36            value = conf.get(section, item)
37            if item.find("&") > -1:
38                item = tuple(item.split("&"))
39            if value.find("&") > -1:
40                value = tuple(value.split("&"))
41            d[section][item] = value
42
43    return d
44
45
46def getConfigDict(cf=config_file):
47    "Checks if already made and only makes if required."
48    global config_dict
49    if config_dict == None:
50        config_dict = makeConfigDict(cf)
51    return config_dict
52
53def makeAnnotationsConfigDict(af):
54    """
55    Parses annotations config file and returns dictionary of annotations.
56    """
57    ad = {}
58    conf = MyCasePreservingConfigParser()
59    conf.read(af)
60
61    # Load up dict
62    for item in conf.options("annotations"):
63        value = conf.get("annotations", item)
64        ad[item] = value
65
66    return ad
67
68def getAnnotationsConfigDict():
69    "Checks if already made and only makes if required."
70    config_dict = getConfigDict()
71    annotations_config_file = config_dict["main"]["annotations_file"]
72    af = os.path.join(base_dir, annotations_config_file)
73    global annotations_config_dict
74    if annotations_config_dict == None:
75        annotations_config_dict = makeAnnotationsConfigDict(af)
76    return annotations_config_dict
77
78if __name__=="__main__":
79    print getConfigDict()
80    print getAnnotationsConfigDict()
Note: See TracBrowser for help on using the repository browser.