Mercurial > hgrepos > Python > libs > ConfigMix
comparison configmix/__init__.py @ 22:6a91db2c2469
A convenience function to load and merge a list of configuration files with different styles
| author | Franz Glasner <f.glasner@feldmann-mg.com> |
|---|---|
| date | Thu, 10 Mar 2016 15:08:20 +0100 |
| parents | 24ba462b9b4b |
| children | 1b8d5c9d294f |
comparison
equal
deleted
inserted
replaced
| 21:ce290b10dac5 | 22:6a91db2c2469 |
|---|---|
| 1 # -*- coding: utf-8 -*- | 1 # -*- coding: utf-8 -*- |
| 2 r""" | 2 r"""A library for helping with configuration files. |
| 3 | 3 |
| 4 :Author: Franz Glasner | 4 :Author: Franz Glasner |
| 5 :License: BSD License. | 5 :License: BSD License. |
| 6 See LICENSE for details. | 6 See LICENSE for details. |
| 7 | 7 |
| 13 __version__ = "0.0.dev0" | 13 __version__ = "0.0.dev0" |
| 14 | 14 |
| 15 | 15 |
| 16 import copy | 16 import copy |
| 17 | 17 |
| 18 from .config import Configuration | |
| 18 | 19 |
| 19 __all__ = [] | 20 |
| 21 __all__ = ["load", "Configuration"] | |
| 22 | |
| 23 | |
| 24 def load(*files): | |
| 25 """Load the given configuration files, merge them in the given order | |
| 26 and return the resulting `Configuration` dictionary. | |
| 27 | |
| 28 """ | |
| 29 if not files: | |
| 30 return Configuration() | |
| 31 else: | |
| 32 ex = merge(None, _load_cfg_from_file(files[0])) | |
| 33 for f in files: | |
| 34 ex = merge(_load_cfg_from_file(f), ex) | |
| 35 return Configuration(ex) | |
| 36 | |
| 37 | |
| 38 def _load_cfg_from_file(filename): | |
| 39 fnl = filename.lower() | |
| 40 if fnl.endswith(".yml") or fnl.endswith("yaml"): | |
| 41 from . import yaml | |
| 42 with open(filename, "rb") as yf: | |
| 43 return yaml.safe_load(yf) | |
| 44 elif fnl.endswith(".py"): | |
| 45 from . import py | |
| 46 return py.load(filename) | |
| 47 elif fnl.endswith(".ini"): | |
| 48 from . import ini | |
| 49 return ini.load(filename) | |
| 50 else: | |
| 51 raise ValueError("Unknown configuration file type for filename " | |
| 52 "%r" % filename) | |
| 20 | 53 |
| 21 | 54 |
| 22 if 0: | 55 if 0: |
| 23 # | 56 # |
| 24 # From: https://github.com/jet9/python-yconfig/blob/master/yconfig.py | 57 # From: https://github.com/jet9/python-yconfig/blob/master/yconfig.py |
