source: TI00-utils/trunk/ndg/utils/config.py @ 1816

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI00-utils/trunk/ndg/utils/config.py@1816
Revision 1816, 2.4 KB checked in by spascoe, 13 years ago (diff)

Small fix that makes config.readfp() work.

Line 
1"""
2Routines for reading the NDG configuration file(s).
3
4All packages can import this module to access the system's NDG
5configation.  Conguration files are read as follows
6
7 1. SafeConfigParser is subclassed so that any call to the read() or
8    readfp() methods examines the section 'ndg.utils.config' for
9    'include' definitions.  Each whitespace-separated string defined
10    as include is treated as a path to another configuration file
11    which will be passed to read().  Paths are interpreted relative to
12    the config file currently being parsed.
13 2. /etc/ndg.conf is read if available
14 3. $HOME/.ndg/ndg.conf is read if available
15
16For example:
17
18  /etc/ndg.conf:
19  [ndg.utils.config]
20  include = /etc/ndg/myconfig.conf
21    ndg_extra.conf
22
23would parse /etc/ndg/myconfig.conf and /etc/ndg_extra.conf.
24
25
26@author: Stephen Pascoe
27"""
28
29from ConfigParser import SafeConfigParser, NoSectionError, NoOptionError
30import os
31
32
33GLOBAL_CONFIG_FILE = '/etc/ndg.conf'
34CONFIG_SECTION = 'ndg.utils.config'
35
36class NdgConfigParser(SafeConfigParser):
37   
38    def __init__(self, configSection, defaults=None):
39        """
40        @param configSection: The section name to read 'include' definitions from.
41        """
42        self._included = []
43        self.configSection = configSection
44        SafeConfigParser.__init__(self, defaults)
45
46    def read(self, filenames, include=True):
47        if isinstance(filenames, basestring):
48            filenames = [filenames]
49        for filename in filenames:
50            SafeConfigParser.read(self, [filename])
51            if include:
52                self.include(os.path.abspath(os.path.dirname(filename)))
53
54    def readfp(self, fp):
55        SafeConfigParser.readfp(self, fp)
56        self.include()
57
58    def include(self, relativeDir=''):
59        """
60        @param relativeDir: include definitions are resolved relative to this directory.
61        """
62
63        try:
64            paths = self.get(self.configSection, 'include').split()
65        except NoSectionError, NoOptionError:
66            return
67
68        for path in paths:
69            if not os.path.isabs(path):
70                path = os.path.join(relativeDir, path)
71            if path in self._included:
72                continue
73            self.read([path], include=False)
74            self._included.append(path)     
75
76config = NdgConfigParser(CONFIG_SECTION)
77config.read([GLOBAL_CONFIG_FILE, '%s/.ndg/ndg.conf' % os.getenv('HOME')])
78
Note: See TracBrowser for help on using the repository browser.