How to use the configparser.MissingSectionHeaderError function in configparser

To help you get started, we’ve selected a few configparser examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github uyuni-project / uyuni / client / tools / mgr-cfg / config_common / local_config.py View on Github external
def read_config_files(self, overrides={}):
        self.overrides.clear()
        self.overrides.update(overrides)

        try:
            self.read(self._get_config_files())
        except ConfigParser.MissingSectionHeaderError:
            e = sys.exc_info()[1]
            print("Config error: line %s, file %s: %s" % (e.lineno,
                e.filename, e))
            sys.exit(1)
github wubinzzu / NeuRec / neurec / util / reader.py View on Github external
def file(path):
    """Returns the configuration settings for a file.

    path -- path to the file
    """
    parser = ConfigParser()

    try:
        with open(path) as file:
            parser.read_file(file)
    except FileNotFoundError:
        raise FileNotFoundError("Could not find file " + str(path) + ". Make sure the file path is correct.")
    except MissingSectionHeaderError:
        raise RuntimeError("Could not find a section header in " + str(path) + '. Added [DEFAULT] to line 1 of this file')

    return parser
github Tribler / tribler / Tribler / Core / Upgrade / config_converter.py View on Github external
tribler_file_loc = os.path.join(state_dir, "tribler.conf")
    if os.path.exists(tribler_file_loc):
        tribler_cfg = RawConfigParser()
        tribler_cfg.read(tribler_file_loc)
        current_config = add_tribler_config(current_config, tribler_cfg)
        os.remove(tribler_file_loc)

    # We also have to update all existing downloads, in particular, rename the section 'downloadconfig' to
    # 'download_defaults'.
    for filename in iglob(os.path.join(state_dir, STATEDIR_CHECKPOINT_DIR, '*.state')):
        download_cfg = RawConfigParser()
        try:
            with open(filename) as cfg_file:
                download_cfg.read_file(cfg_file, source=filename)
        except MissingSectionHeaderError:
            logger.error("Removing download state file %s since it appears to be corrupt", filename)
            os.remove(filename)

        try:
            download_items = download_cfg.items("downloadconfig")
            download_cfg.add_section("download_defaults")
            for download_item in download_items:
                download_cfg.set("download_defaults", download_item[0], download_item[1])
            download_cfg.remove_section("downloadconfig")
            with open(filename, "w") as output_config_file:
                download_cfg.write(output_config_file)
        except (NoSectionError, DuplicateSectionError):
            # This item has already been converted
            pass

    return current_config
github pyscaffold / configupdater / src / configupdater / configupdater.py View on Github external
if sectname in self._sections:
                        if self._strict and sectname in elements_added:
                            raise DuplicateSectionError(sectname, fpname,
                                                        lineno)
                        cursect = self._sections[sectname]
                        elements_added.add(sectname)
                    else:
                        cursect = self._dict()
                        self._sections[sectname] = cursect
                        elements_added.add(sectname)
                    # So sections can't start with a continuation line
                    optname = None
                    self._add_section(sectname, line)  # HOOK
                # no section header in the file?
                elif cursect is None:
                    raise MissingSectionHeaderError(fpname, lineno, line)
                # an option line?
                else:
                    mo = self._optcre.match(value)
                    if mo:
                        optname, vi, optval = mo.group('option', 'vi', 'value')
                        if not optname:
                            e = self._handle_error(e, fpname, lineno, line)
                        # optname = self.optionxform(optname.rstrip())
                        # keep original case of key
                        optname = optname.rstrip()
                        if (self._strict and
                                (sectname, optname) in elements_added):
                            raise DuplicateOptionError(sectname, optname,
                                                       fpname, lineno)
                        elements_added.add((sectname, optname))
                        # This check is fine because the OPTCRE cannot
github olofk / fusesoc / fusesoc / capi1 / fusesocconfigparser.py View on Github external
except IndexError:
            raise SyntaxError("Could not find API version in " + config_file)
        if sys.version[0] == '2':
            exceptions = (configparser.ParsingError,
                          configparser.DuplicateSectionError)
        else:
            exceptions = (configparser.ParsingError,
                          configparser.DuplicateSectionError,
                          configparser.DuplicateOptionError)
        try:
            if sys.version[0] == '2':
                self.readfp(f)
            else:
                self.read_file(f)
        except configparser.MissingSectionHeaderError:
            raise SyntaxError("Missing section header")
        except exceptions as e:
            raise SyntaxError(e.message)
github pyscaffold / pyscaffold / src / pyscaffold / contrib / configupdater.py View on Github external
if sectname in self._sections:
                        if self._strict and sectname in elements_added:
                            raise DuplicateSectionError(sectname, fpname,
                                                        lineno)
                        cursect = self._sections[sectname]
                        elements_added.add(sectname)
                    else:
                        cursect = self._dict()
                        self._sections[sectname] = cursect
                        elements_added.add(sectname)
                    # So sections can't start with a continuation line
                    optname = None
                    self._add_section(sectname, line)  # HOOK
                # no section header in the file?
                elif cursect is None:
                    raise MissingSectionHeaderError(fpname, lineno, line)
                # an option line?
                else:
                    mo = self._optcre.match(value)
                    if mo:
                        optname, vi, optval = mo.group('option', 'vi', 'value')
                        if not optname:
                            e = self._handle_error(e, fpname, lineno, line)
                        optname = self.optionxform(optname.rstrip())
                        if (self._strict and
                                (sectname, optname) in elements_added):
                            raise DuplicateOptionError(sectname, optname,
                                                       fpname, lineno)
                        elements_added.add((sectname, optname))
                        # This check is fine because the OPTCRE cannot
                        # match if it would set optval to None
                        if optval is not None:
github iTaybb / iQuality / code / Config.py View on Github external
def loadFromIni(self):
		'Loads data from INI file'
		if not os.path.exists(self.ini_path):
			return
			
		obj = configparser.RawConfigParser()
		obj.optionxform = unicode # Enable case sensitive
		try:
			obj.readfp(codecs.open(self.ini_path, 'rb', 'utf-8'))
		except configparser.MissingSectionHeaderError:
			# os.unlink(self.ini_path)
			return
		
		if not 'Settings' in obj.sections():
			return
		
		for k, v in obj.items('Settings'):
			if k in vars_to_override:
				continue
				
			if k in vars_to_eval:
				self.d[k] = eval(v)
			else:
				self.d[k] = v
github osantana / prettyconf / prettyconf / loaders.py View on Github external
def _parse(self):
        if self._initialized:
            return

        with open(self.filename) as inifile:
            try:
                self.parser.read_file(inifile)
            except (UnicodeDecodeError, MissingSectionHeaderError):
                raise InvalidConfigurationFile()

        if not self.parser.has_section(self.section):
            raise MissingSettingsSection("Missing [{}] section in {}".format(self.section, self.filename))

        self._initialized = True
github Rostlab / nalaf / demo.py View on Github external
if not args.quick_nl:
            print("Labeling")
            TmVarLabeler().label(dataset)
            print("Feature Generation")
            TmVarFeatureGenerator().generate(dataset)
            # print("Window Feature Generation")
            # WindowFeatureGenerator().generate(dataset)

            crf = CRFSuite(crf_path)
            print("CRFstart")
            crf.create_input_file(dataset, 'train')
            crf.learn()
            crf.create_input_file(dataset, 'test')
            crf.tag()

    except (configparser.MissingSectionHeaderError, configparser.NoSectionError, configparser.NoOptionError):
        print(config_ini_error, file=sys.stderr)
github hay86 / fdfs_client-py / fdfs_client / utils.py View on Github external
mo = self.SECTCRE.match(line)
                if mo:
                    sectname = mo.group('header')
                    if sectname in self._sections:
                        cursect = self._sections[sectname]
                    elif sectname == DEFAULTSECT:
                        cursect = self._defaults
                    else:
                        cursect = self._dict()
                        cursect['__name__'] = sectname
                        self._sections[sectname] = cursect
                    # So sections can't start with a continuation line
                    optname = None
                # no section header in the file?
                elif cursect is None:
                    raise MissingSectionHeaderError(fpname, lineno, line)
                # an option line?
                else:
                    mo = self.OPTCRE.match(line)
                    if mo:
                        optname, vi, optval = mo.group('option', 'vi', 'value')
                        if vi in ('=', ':') and ';' in optval:
                            # ';' is a comment delimiter only if it follows
                            # a spacing character
                            pos = optval.find(';')
                            if pos != -1 and optval[pos - 1].isspace():
                                optval = optval[:pos]
                        optval = optval.strip()
                        # allow empty values
                        if optval == '""':
                            optval = ''
                        optname = self.optionxform(optname.rstrip())