def save_config(): config = configparser.ConfigParser(allow_no_value=True) config.read("./config.ini") updater = ConfigUpdater() try: updater.read_file('config.ini') except Exception as rt_err: raise rt_err # config.set('Configuration', 'locale', self.config['locale']) # config.set('Configuration', 'font-size', self.config['font-size']) # Try New format all together for section_name in updater.sections(): print(section_name)
def config_updater_factory(config: Box) -> Tuple[Path, ConfigUpdater]: """Return a ConfigUpdater object and the path obj to the config file. Note, the config file must exist. There isn't too much error checking in this function. E. g. that will not work with an empty config file. """ config_updater_data = copy.deepcopy(config) if "config_file_path" in config_updater_data: path = Path(config_updater_data.pop("config_file_path")) else: raise AttributeError( "The config is missing the config_file_path. This should not happen." ) config_updater = ConfigUpdater() to_add = [] with open(path.as_posix()) as fh: config_updater.read_file(fh) for section in config_updater_data: if config_updater.has_section(section): config_updater_section = config_updater[section] last_option = config_updater_section.options()[-1] for option, value in config[section].items(): if option in config_updater_section: config_updater_section[option].value = value else: config_updater_section[last_option].add_after.option( option, value) last_option = option config_updater[section] = config_updater_section else: tmp_updater = ConfigUpdater() section_txt = f"[{section}]\n" + "\n".join( (f"{option}: {value}" for option, value in config_updater_data[section].items())) tmp_updater.read_string(section_txt) to_add.append(tmp_updater[section]) if to_add: last_section = config_updater[config_updater.sections()[-1]] for section in to_add: # Add a new line for readability config_updater[last_section.name].add_after.space().section( section) last_section = section return path, config_updater
def test_read_file_like(setup_cfg_path): updater = ConfigUpdater() with open(setup_cfg_path) as fp: updater.read_file(fp) fp = StringIO() updater.read_file(fp)
def test_read_file_with_string(): updater = ConfigUpdater() with pytest.raises(RuntimeError): updater.read_file('path/to/file.cfg')