import configparser import os class Conf(object): _confobj = configparser.ConfigParser(os.environ) _cfgfiles = [] debug = None def __init__(self, filename=None, debug=None): if debug: self.set_debug(debug) filenames = [] if filename: filenames.append(filename) filenames.append(f'{os.environ.get("HOME")}/etc/userconfig2.conf') 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 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.NoOptionError) 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()