Mercurial > hgrepos > Python > libs > ConfigMix
changeset 20:9bdc4e421415
A "load()" function for INI-style configuration files that extracts given sections into the resulting dictonary.
Applies also type conversions and configparser-style string interpolations.
| author | Franz Glasner <f.glasner@feldmann-mg.com> |
|---|---|
| date | Thu, 10 Mar 2016 13:06:31 +0100 |
| parents | 04505a8dbfc0 |
| children | ce290b10dac5 |
| files | configmix/ini.py |
| diffstat | 1 files changed, 30 insertions(+), 1 deletions(-) [+] |
line wrap: on
line diff
--- a/configmix/ini.py Thu Mar 10 11:11:17 2016 +0100 +++ b/configmix/ini.py Thu Mar 10 13:06:31 2016 +0100 @@ -13,11 +13,19 @@ from configparser import SafeConfigParser, NoSectionError, NoOptionError except ImportError: from ConfigParser import SafeConfigParser, NoSectionError, NoOptionError +try: + from collections import OrderedDict as DictImpl +except ImportError: + try: + from ordereddict import OrderedDict as DictImpl + except ImportError: + DictImpl = dict from .compat import PY2 -__all__ = ["INIConfigParser", "NoSectionError", "NoOptionError"] +__all__ = ["INIConfigParser", "NoSectionError", "NoOptionError", + "load"] class INIConfigParser(SafeConfigParser): @@ -92,3 +100,24 @@ _BOOL_CVT = {'1': True, 'yes': True, 'true': True, 'on': True, '0': False, 'no': False, 'false': False, 'off': False} + + +def load(filename, extract=["config"]): + """Load a single INI file and read/interpolate the sections given in + `extract`. + + Flattens the given sections into the resulting dictionary. + + """ + conf = DictImpl() + ini = INIConfigParser(filename) + for sect in extract: + try: + cfg = ini.options(sect) + except NoSectionError: + pass + else: + for option in cfg: + value = ini.getx(sect, option) + conf[option] = value + return conf
