3 from __future__ import print_function
6 from ConfigParser import RawConfigParser, NoSectionError, NoOptionError
7 except ImportError: # py3
8 from configparser import RawConfigParser, NoSectionError, NoOptionError
11 __all__ = ['get_config']
14 def _find_config_dirs_posix():
16 if 'XDG_CONFIG_HOME' in os.environ:
17 config_dirs.append(os.environ['XDG_CONFIG_HOME'])
18 if 'XDG_CONFIG_DIRS' in os.environ:
19 config_dirs.extend(os.environ['XDG_CONFIG_DIRS'].split(':'))
20 home_config = os.path.expanduser('~/.config')
21 if home_config not in config_dirs:
22 config_dirs.append(home_config)
26 def find_config_dirs():
27 if os.name == 'posix':
28 return _find_config_dirs_posix()
32 def find_config_file(config_dirs=None, config_filename='m_librarian.conf'):
33 if config_dirs is None:
34 config_dirs = find_config_dirs()
36 ml_conf_file = os.path.join(d, config_filename)
37 if os.path.exists(ml_conf_file):
46 class ConfigWrapper(object):
47 def __init__(self, config):
50 def get(self, section, option, default=None):
52 return self.config.get(section, option)
53 except (NoSectionError, NoOptionError):
56 def set(self, section, option, value):
57 self.config.set(section, option, value)
59 def getint(self, section, option, default=0):
61 return self.config.getint(section, option)
62 except (NoSectionError, NoOptionError):
64 # Do not catch ValueError here, it must be propagated
66 def getlist(self, section, option, default=None, sep=None):
67 value = self.get(section, option)
72 return value.split(sep)
74 def getpath(self, section, option, default=os.path.curdir):
75 path = self.get(section, option, default=default)
76 return os.path.expanduser(os.path.expandvars(path))
79 def get_config(config_path=None):
81 if _ml_config is None:
82 _ml_config = RawConfigParser()
83 if config_path is None:
84 config_path = find_config_file()
85 if config_path is not None:
86 _ml_config.read(config_path)
87 _ml_config = ConfigWrapper(_ml_config)
92 config_dirs = find_config_dirs()
93 print("Config dirs:", config_dirs)
94 print("Config file:", find_config_file(config_dirs))
97 if __name__ == '__main__':