pyuserconfig/userconfig/cfgfile.py

68 lines
2.4 KiB
Python
Raw Normal View History

import configparser
import os
import sys
class Conf(object):
_confobj = None
_cfgfiles = []
debug = None
def __init__(self, filename=None, debug=None, force_filename=False):
if debug:
self.set_debug(debug)
self._confobj = configparser.ConfigParser(dict(HOME=os.environ.get('HOME')))
filenames = []
if not force_filename:
# default config files are $HOME/etc/userconfig2.conf and
# {sys.prefix}/etc/userconfig2.conf
if os.path.isfile(f'{os.environ.get("HOME")}/etc/userconfig2.conf'):
filenames.append(f'{os.environ.get("HOME")}/etc/userconfig2.conf')
if os.path.isfile(f'{sys.prefix}/etc/userconfig2.conf'):
filenames.append(f'{sys.prefix}/etc/userconfig2.conf')
# supplied filename will be read last, has highest priority
if filename:
filenames.append(filename)
ret = self.set_filenames(filenames)
if not ret:
raise ValueError(f'Cannot open either configuration file: {",".join(filenames)}')
def set_debug(self, debug):
self.debug = debug
def set_filenames(self, filenames):
ret = self._confobj.read(filenames)
if len(ret) == 0:
return None
self._cfgfiles = ret
if self.debug:
self.debug.stdout("Read config files: %s" % ", ".join(filenames), 2)
return ret
def get(self, option, boolean=False, section='userconfig'):
try:
if boolean:
return self._confobj.getboolean(section, option)
else:
return self._confobj.get(section, option)
except (configparser.NoOptionError, configparser.NoSectionError) as e:
raise ValueError(f'Option {option} does not exist in section {section}: {e}')
def set(self, option, value, section='userconfig'):
try:
self._confobj.set(section, option, value)
except configparser.NoSectionError as e:
raise ValueError(f'Section {section} does not exist: {e}')
def get_items(self, section='userconfig'):
try:
return self._confobj.items(section)
except configparser.NoSectionError as e:
raise ValueError(f'Section {section} does not exist: {e}')
def check(self, option, section='userconfig'):
return self._confobj.has_option(section, option)
def sections(self):
return self._confobj.sections()