Mercurial > hgrepos > Python > libs > ConfigMix
comparison configmix/py.py @ 6:caaaddb11db1
Evaluating Python configuration files
| author | Franz Glasner <hg@dom66.de> |
|---|---|
| date | Wed, 09 Mar 2016 00:51:46 +0100 |
| parents | |
| children | 04505a8dbfc0 |
comparison
equal
deleted
inserted
replaced
| 5:dc058099a4cb | 6:caaaddb11db1 |
|---|---|
| 1 # -*- coding: utf-8 -*- | |
| 2 r"""Read configuration settings from Python files | |
| 3 | |
| 4 """ | |
| 5 | |
| 6 from __future__ import division, absolute_import, print_function | |
| 7 | |
| 8 import locale | |
| 9 | |
| 10 from .compat import PY2 | |
| 11 | |
| 12 | |
| 13 __all__ = ["load"] | |
| 14 | |
| 15 | |
| 16 def load(filename, extract=None): | |
| 17 if extract is not None: | |
| 18 if not isinstance(extract, (type([]), type(tuple()), type(set()), )): | |
| 19 raise TypeError("`extract' must be a sequence") | |
| 20 gcontext = dict() | |
| 21 lcontext = dict() | |
| 22 if PY2: | |
| 23 filename2 = filename.encode(locale.getpreferredencoding()) | |
| 24 if PY2: | |
| 25 execfile(filename2, gcontext, lcontext) | |
| 26 else: | |
| 27 # "rb" mode allows Python to derive the encoding automatically | |
| 28 with open(filename, "rb") as vf: | |
| 29 code = compile(vf.read(), filename, "exec") | |
| 30 exec(code, gcontext, lcontext) | |
| 31 if extract is None: | |
| 32 if "__all__" in lcontext: | |
| 33 extract = lcontext["__all__"] | |
| 34 else: | |
| 35 extract = [k for k in lcontext if not k.startswith('_')] | |
| 36 # don't bail on non-existing keys | |
| 37 extract = [v for v in extract if v in lcontext] | |
| 38 return dict(zip(extract, [lcontext[v] for v in extract])) |
