Mercurial > hgrepos > Python > libs > ConfigMix
comparison configmix/ini.py @ 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 | 36fa039f7e11 |
| children | ce290b10dac5 |
comparison
equal
deleted
inserted
replaced
| 19:04505a8dbfc0 | 20:9bdc4e421415 |
|---|---|
| 11 import locale | 11 import locale |
| 12 try: | 12 try: |
| 13 from configparser import SafeConfigParser, NoSectionError, NoOptionError | 13 from configparser import SafeConfigParser, NoSectionError, NoOptionError |
| 14 except ImportError: | 14 except ImportError: |
| 15 from ConfigParser import SafeConfigParser, NoSectionError, NoOptionError | 15 from ConfigParser import SafeConfigParser, NoSectionError, NoOptionError |
| 16 try: | |
| 17 from collections import OrderedDict as DictImpl | |
| 18 except ImportError: | |
| 19 try: | |
| 20 from ordereddict import OrderedDict as DictImpl | |
| 21 except ImportError: | |
| 22 DictImpl = dict | |
| 16 | 23 |
| 17 from .compat import PY2 | 24 from .compat import PY2 |
| 18 | 25 |
| 19 | 26 |
| 20 __all__ = ["INIConfigParser", "NoSectionError", "NoOptionError"] | 27 __all__ = ["INIConfigParser", "NoSectionError", "NoOptionError", |
| 28 "load"] | |
| 21 | 29 |
| 22 | 30 |
| 23 class INIConfigParser(SafeConfigParser): | 31 class INIConfigParser(SafeConfigParser): |
| 24 | 32 |
| 25 """A case sensitive config parser that returns all-unicode string | 33 """A case sensitive config parser that returns all-unicode string |
| 90 else: | 98 else: |
| 91 return v | 99 return v |
| 92 | 100 |
| 93 _BOOL_CVT = {'1': True, 'yes': True, 'true': True, 'on': True, | 101 _BOOL_CVT = {'1': True, 'yes': True, 'true': True, 'on': True, |
| 94 '0': False, 'no': False, 'false': False, 'off': False} | 102 '0': False, 'no': False, 'false': False, 'off': False} |
| 103 | |
| 104 | |
| 105 def load(filename, extract=["config"]): | |
| 106 """Load a single INI file and read/interpolate the sections given in | |
| 107 `extract`. | |
| 108 | |
| 109 Flattens the given sections into the resulting dictionary. | |
| 110 | |
| 111 """ | |
| 112 conf = DictImpl() | |
| 113 ini = INIConfigParser(filename) | |
| 114 for sect in extract: | |
| 115 try: | |
| 116 cfg = ini.options(sect) | |
| 117 except NoSectionError: | |
| 118 pass | |
| 119 else: | |
| 120 for option in cfg: | |
| 121 value = ini.getx(sect, option) | |
| 122 conf[option] = value | |
| 123 return conf |
