# HG changeset patch # User Franz Glasner # Date 1457611591 -3600 # Node ID 9bdc4e421415668b4c0fc831671884085c6b0cfc # Parent 04505a8dbfc071a1b28ac840772cf04cff4ba31f 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. diff -r 04505a8dbfc0 -r 9bdc4e421415 configmix/ini.py --- 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