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

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

Added config file and parser for annotations.

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