Extract constant for config file section

.. and improve config error reporting
This commit is contained in:
Sebastian Pipping 2012-01-31 02:24:05 +01:00
parent 62f0f02fa7
commit 692284f41d
1 changed files with 9 additions and 7 deletions

View File

@ -9,6 +9,8 @@ import sys
import ConfigParser import ConfigParser
_SECTION = 'client-barcode'
_KEYS = ( _KEYS = (
# Key, type, default # Key, type, default
('CLIENT_DEBUG', bool, False), # Should go first to enable debugging as early as possible ('CLIENT_DEBUG', bool, False), # Should go first to enable debugging as early as possible
@ -32,28 +34,28 @@ class Settings:
cp = ConfigParser.ConfigParser(_DEFAULTS) cp = ConfigParser.ConfigParser(_DEFAULTS)
if not cp.read(filename): if not cp.read(filename):
print('FATAL: Config file %s could not be parsed.' % (filename), file=sys.stderr) print('FATAL: Config file "%s" could not be parsed.' % (filename), file=sys.stderr)
return False return False
valid = True valid = True
for key, _type, dummy in _KEYS + additional_keys: for key, _type, dummy in _KEYS + additional_keys:
try: try:
if _type is bool: if _type is bool:
value = cp.getboolean('client-barcode', key) value = cp.getboolean(_SECTION, key)
else: else:
value = cp.get('client-barcode', key) value = cp.get(_SECTION, key)
except ValueError: except ValueError:
print('ERROR: Key %s in config file %s must be of type %s.' \ print('ERROR: Key "%s" in config file "%s" must be of type "%s".' \
% (key, filename, _type.__name__), file=sys.stderr) % (key, filename, _type.__name__), file=sys.stderr)
valid = False valid = False
except ConfigParser.NoOptionError: except ConfigParser.NoOptionError:
print('ERROR: Config file %s misses required key %s.' \ print('ERROR: Config file "%s" misses required key "%s.%s".' \
% (filename, key), file=sys.stderr) % (filename, _SECTION, key), file=sys.stderr)
valid = False valid = False
else: else:
setattr(self, key, value) setattr(self, key, value)
if self.CLIENT_DEBUG: if self.CLIENT_DEBUG:
print('DEBUG: CONFIG: %s=%s("%s")' % (key, type(value).__name__, value)) print('DEBUG: CONFIG: %s.%s=%s("%s")' % (_SECTION, key, type(value).__name__, value))
return valid return valid