Python configobj.ConfigObjError() Examples

The following are 9 code examples of configobj.ConfigObjError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module configobj , or try the search function .
Example #1
Source File: config.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def parse(self, config, defaults=None):
        """Parse the conf

        :param config: Configuration to parse
        :type config: str, list or File

        :param defaults: Default options
        :type defaults: dict
        """
        self.conf = {}
        self.conffile = config
        self.section = None
        if defaults is not None or not hasattr(self, 'defaults'):
            self.defaults = defaults
        self.validator = validate.Validator()
        try:
            self.conf = configobj.ConfigObj(config, encoding='utf-8')
            self.mtime = os.path.getmtime(self.conffile)
        except configobj.ConfigObjError as exp:
            # We were unable to parse the config
            self.logger.critical('Unable to parse configuration')
            raise exp 
Example #2
Source File: config.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def parse(self, config, defaults=None):
        """Parse the conf

        :param config: Configuration to parse
        :type config: str, list or File

        :param defaults: Default options
        :type defaults: dict
        """
        self.conf = {}
        self.conffile = config
        self.section = None
        if defaults is not None or not hasattr(self, 'defaults'):
            self.defaults = defaults
        self.validator = validate.Validator()
        try:
            self.conf = configobj.ConfigObj(config, encoding='utf-8')
            self.mtime = os.path.getmtime(self.conffile)
        except configobj.ConfigObjError as exp:
            # We were unable to parse the config
            self.logger.critical('Unable to parse configuration')
            raise exp 
Example #3
Source File: config.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def parse(self, config, defaults=None):
        """Parse the conf

        :param config: Configuration to parse
        :type config: str, list or File

        :param defaults: Default options
        :type defaults: dict
        """
        self.conf = {}
        self.conffile = config
        self.section = None
        if defaults is not None or not hasattr(self, 'defaults'):
            self.defaults = defaults
        self.validator = validate.Validator()
        try:
            self.conf = configobj.ConfigObj(config, encoding='utf-8')
            self.mtime = os.path.getmtime(self.conffile)
        except configobj.ConfigObjError as exp:
            # We were unable to parse the config
            self.logger.critical('Unable to parse configuration')
            raise exp 
Example #4
Source File: config.py    From athenacli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def read_config_file(f):
    """Read a config file."""

    if isinstance(f, basestring):
        f = os.path.expanduser(f)

    try:
        config = ConfigObj(f, interpolation=False, encoding='utf8')
    except ConfigObjError as e:
        log(LOGGER, logging.ERROR, "Unable to parse line {0} of config file "
            "'{1}'.".format(e.line_number, f))
        log(LOGGER, logging.ERROR, "Using successfully parsed config values.")
        return e.config
    except (IOError, OSError) as e:
        log(LOGGER, logging.WARNING, "You don't have permission to read "
            "config file '{0}'.".format(e.filename))
        return None

    return config 
Example #5
Source File: config.py    From cli_helpers with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def read_config_file(self, f):
        """Read a config file *f*.

        :param str f: The path to a file to read.
        """
        configspec = self.default_file if self.validate else None
        try:
            config = ConfigObj(infile=f, configspec=configspec,
                               interpolation=False, encoding='utf8')
        except ConfigObjError as e:
            logger.warning(
                'Unable to parse line {} of config file {}'.format(
                    e.line_number, f))
            config = e.config

        valid = True
        if self.validate:
            valid = config.validate(Validator(), preserve_errors=True,
                                    copy=True)
        if bool(config):
            self.config_filenames.append(config.filename)

        return config, valid 
Example #6
Source File: helpers.py    From panoptes with Apache License 2.0 5 votes vote down vote up
def parse_config_file(config_file, config_spec_file):

    assert validators.PanoptesValidators.valid_nonempty_string(config_file), u'config_file must be a non-empty str'
    assert validators.PanoptesValidators.valid_nonempty_string(config_spec_file), \
        u'config_spec_file must be a non empty str'

    try:
        config = ConfigObj(config_file, configspec=config_spec_file, interpolation=u'template', file_error=True)
    except IOError as e:
        raise PanoptesConfigurationParsingError(u'Error reading file: %s' % str(e))
    except ConfigObjError as e:
        raise PanoptesConfigurationParsingError(u'Error parsing config file "%s": %s' % (config_file, str(e)))

    validator = Validator()
    result = config.validate(validator, preserve_errors=True)

    if result is not True:
        errors = u''
        for (section_list, key, error) in flatten_errors(config, result):
            if key is None:
                errors += u'Section(s) ' + u','.join(section_list) + u' are missing\n'
            else:
                errors += u'The "' + key + u'" key in section "' + u','.join(section_list) + u'" failed validation\n'

        raise PanoptesConfigurationParsingError(u'Error parsing the configuration file: %s' % errors)

    return config 
Example #7
Source File: utilities.py    From picochess with GNU General Public License v3.0 5 votes vote down vote up
def write_picochess_ini(key: str, value):
    """Update picochess.ini config file with key/value."""
    try:
        config = ConfigObj('picochess.ini')
        config[key] = value
        config.write()
    except (ConfigObjError, DuplicateError) as conf_exc:
        logging.exception(conf_exc) 
Example #8
Source File: test_config.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_config_init():
    casters = ['string_lower_list', 'force_string', 'boolean_or_string']
    fd, tmpfile = mkstemp()
    os.write(fd, TEST_CONFIG)
    os.close(fd)

    fd, wrong = mkstemp()
    os.write(fd, TEST_CONFIG_FAILURE)
    os.close(fd)

    config = BUIConfig(tmpfile)
    with pytest.raises(configobj.ConfigObjError):
        BUIConfig(wrong, defaults={})

    assert config.safe_get('backend', section='Global') == 'something'
    assert config.safe_get('timeout', 'integer', 'Global') == 12

    config.default_section('Production')

    assert config.safe_get('duplicate') == 'cat'
    assert config.safe_get('duplicate', section='Global') == 'nyan'
    assert config.safe_get('run', 'boolean_or_string') is True
    assert config.safe_get('sql', 'boolean_or_string') == 'none'

    array = config.safe_get('array', 'string_lower_list')
    assert array[1] == 'values'
    assert array[0] == 'some'
    assert isinstance(config.safe_get('array'), list)

    assert config.safe_get('array', 'force_string') == 'some,VALUES'

    for cast in casters:
        # safe_get is safe and shouldn't raise any exception
        assert config.safe_get('i iz not in ze config!', cast) is None

    os.unlink(tmpfile)
    os.unlink(wrong) 
Example #9
Source File: config.py    From landscape-client with GNU General Public License v2.0 5 votes vote down vote up
def _get_config_object(self, alternative_config=None):
        """Create a L{ConfigObj} consistent with our preferences.

        @param config_source: Optional readable source to read from instead of
            the default configuration file.
        """
        config_source = alternative_config or self.get_config_filename()
        # Setting list_values to False prevents ConfigObj from being "smart"
        # about lists (it now treats them as strings). See bug #1228301 for
        # more context.
        # Setting raise_errors to False causes ConfigObj to batch all parsing
        # errors into one ConfigObjError raised at the end of the parse instead
        # of raising the first one and then exiting.  This also allows us to
        # recover the good config values in the error handler below.
        # Setting write_empty_values to True prevents configObj writes
        # from writing "" as an empty value, which get_plugins interprets as
        # '""' which search for a plugin named "".  See bug #1241821.
        try:
            config_obj = ConfigObj(config_source, list_values=False,
                                   raise_errors=False, write_empty_values=True)
        except ConfigObjError as e:
            logger = getLogger()
            logger.warn(str(e))
            # Good configuration values are recovered here
            config_obj = e.config
        return config_obj