Python configparser.Error() Examples

The following are 30 code examples for showing how to use configparser.Error(). These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module configparser , or try the search function .

Example 1
Project: qutebrowser   Author: qutebrowser   File: configfiles.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _handle_error(self, action: str, name: str) -> typing.Iterator[None]:
        """Catch config-related exceptions and save them in self.errors."""
        try:
            yield
        except configexc.ConfigFileErrors as e:
            for err in e.errors:
                new_err = err.with_text(e.basename)
                self.errors.append(new_err)
        except configexc.Error as e:
            text = "While {} '{}'".format(action, name)
            self.errors.append(configexc.ConfigErrorDesc(text, e))
        except urlmatch.ParseError as e:
            text = "While {} '{}' and parsing pattern".format(action, name)
            self.errors.append(configexc.ConfigErrorDesc(text, e))
        except keyutils.KeyParseError as e:
            text = "While {} '{}' and parsing key".format(action, name)
            self.errors.append(configexc.ConfigErrorDesc(text, e)) 
Example 2
Project: qutebrowser   Author: qutebrowser   File: configfiles.py    License: GNU General Public License v3.0 6 votes vote down vote up
def init() -> None:
    """Initialize config storage not related to the main config."""
    global state

    try:
        state = StateConfig()
    except (configparser.Error, UnicodeDecodeError) as e:
        msg = "While loading state file from {}".format(standarddir.data())
        desc = configexc.ConfigErrorDesc(msg, e)
        raise configexc.ConfigFileErrors('state', [desc], fatal=True)

    # Set the QSettings path to something like
    # ~/.config/qutebrowser/qsettings/qutebrowser/qutebrowser.conf so it
    # doesn't overwrite our config.
    #
    # This fixes one of the corruption issues here:
    # https://github.com/qutebrowser/qutebrowser/issues/515

    path = os.path.join(standarddir.config(auto=True), 'qsettings')
    for fmt in [QSettings.NativeFormat, QSettings.IniFormat]:
        QSettings.setPath(fmt, QSettings.UserScope, path) 
Example 3
Project: MatchingMarkets.py   Author: QuantEcon   File: solvers.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def callSolver(self, isMIP):
            """Solves the problem with cplex
            """
            #solve the problem
            self.cplexTime = -clock()
            if isMIP and self.mip:
                status= CPLEX_DLL.lib.CPXmipopt(self.env, self.hprob)
                if status != 0:
                    raise PulpSolverError("Error in CPXmipopt status="
                                        + str(status))
            else:
                status = CPLEX_DLL.lib.CPXlpopt(self.env, self.hprob)
                if status != 0:
                    raise PulpSolverError("Error in CPXlpopt status="
                                            + str(status))
            self.cplexTime += clock() 
Example 4
Project: vcm   Author: willasaywhat   File: vcm.py    License: GNU General Public License v3.0 6 votes vote down vote up
def write_global_vcm(self):
        print(f"Creating global config file with defaults in {GLOBAL_CONFIG_LOCATION}")

        global global_config
        global_config = configparser.RawConfigParser()
        global_config.add_section('GlobalSettings')

        global_config.set('GlobalSettings', 'openssl_binary', self.open_ssl_binary)

        global_config_file = os.path.expanduser(GLOBAL_CONFIG_LOCATION)

        with open(global_config_file, 'w') as configfile:
            try:
                global_config.write(configfile)
            except configparser.Error as ex:
                print(f"Error writing config file: {global_config_file} : {ex.message}")
                return 
Example 5
Project: vcm   Author: willasaywhat   File: vcm.py    License: GNU General Public License v3.0 6 votes vote down vote up
def write_project_vcm(self, project_name, local_folder, remote_folder, url_targets):
        project_config = configparser.RawConfigParser()
        project_config.add_section('ProjectSettings')
        project_config.set('ProjectSettings', 'project_name', project_name)
        project_config.set('ProjectSettings', 'local_path', os.path.join(local_folder, ''))
        project_config.set('ProjectSettings', 'remote_path', os.path.join(remote_folder, ''))
        project_config.set('ProjectSettings', 'url_targets', url_targets)

        project_vmc_filename = os.path.join(local_folder, '.vcm')

        with open(project_vmc_filename, 'w') as configfile:
            try:
                project_config.write(configfile)
            except configparser.Error as ex:
                print(f"Error writing config file: {project_vmc_filename} : {ex.message}")
                return 
Example 6
Project: vcm   Author: willasaywhat   File: vcm.py    License: GNU General Public License v3.0 6 votes vote down vote up
def nikto():
    try:
        project_config = VcmProjectConfig()
        project_config.read_project_vcm()
    except ValueError as ex:
        print(ex)
        return

    if not click.confirm('Run nikto against the following targets: %s' % ', '.join(project_config.targets)):
        return

    # Nikto takes multiple hosts from a file
    # BUT bear in mind advice from: https://github.com/sullo/nikto/wiki/Basic-Testing
    # ie run scans separately so that memory is freed each time.
    for t in project_config.targets:
        output_filename = os.path.join(project_config.artifacts_folder,
                                       f"nikto_{urlparse(t).netloc}_{time.time()}.html")
        try:
            # nikto -h https://www.test.com -ssl -Format html -output .
            args = ["nikto", "-h", t, '-ssl', '-Format', 'html', '-output', output_filename]

            print(args)
            call(args)
        except Exception as ex:
            print(f"Error writing nikto output to: {output_filename} : {ex}") 
Example 7
Project: twtxt   Author: buckket   File: config.py    License: MIT License 6 votes vote down vote up
def from_file(cls, file):
        """Try loading given config file.

        :param str file: full path to the config file to load
        """
        if not os.path.exists(file):
            raise ValueError("Config file not found.")

        try:
            config_parser = configparser.ConfigParser()
            config_parser.read(file)

            configuration = cls(file, config_parser)
            if not configuration.check_config_sanity():
                raise ValueError("Error in config file.")
            else:
                return configuration
        except configparser.Error:
            raise ValueError("Config file is invalid.") 
Example 8
Project: atomic-reactor   Author: containerbuildsystem   File: yum.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def is_valid(self):
        # Using BytesIO as configparser in 2.7 can't work with unicode
        # see http://bugs.python.org/issue11597
        with BytesIO(self.content) as buf:
            self.config = configparser.ConfigParser()
            try:
                try:
                    # Try python3 method
                    self.config.read_string(self._content)
                except AttributeError:
                    # Fall back to python2 method
                    self.config.readfp(buf)  # pylint: disable=deprecated-method
            except configparser.Error:
                logger.warning("Invalid repo file found: '%s'", self.content)
                return False
            else:
                return True 
Example 9
Project: gtg   Author: getting-things-gnome   File: application.py    License: GNU General Public License v3.0 6 votes vote down vote up
def init_plugin_engine(self):
        """Setup the plugin engine."""

        self.plugin_engine = PluginEngine()
        plugin_api = PluginAPI(self.req, self)
        self.plugin_engine.register_api(plugin_api)

        try:
            enabled_plugins = self.config_plugins.get("enabled")
        except configparser.Error:
            enabled_plugins = []

        for plugin in self.plugin_engine.get_plugins():
            plugin.enabled = plugin.module_name in enabled_plugins

        self.plugin_engine.activate_plugins() 
Example 10
Project: gtg   Author: getting-things-gnome   File: config.py    License: GNU General Public License v3.0 6 votes vote down vote up
def open_config_file(config_file):
    """ Opens config file and makes additional checks

    Creates config file if it doesn't exist and makes sure it is readable and
    writable by user. That prevents surprise when user is not able to save
    configuration when exiting the app.
    """
    dirname = os.path.dirname(config_file)
    if not os.path.exists(dirname):
        os.makedirs(dirname)
    if not os.path.exists(config_file):
        open(config_file, "w").close()
    if not os.access(config_file, os.R_OK | os.W_OK):
        raise Exception("File " + config_file + " is a configuration file "
                        "for gtg, but it cannot be read or written. "
                        "Please check it")
    config = configparser.ConfigParser()
    try:
        config.read(config_file)
    except configparser.Error as e:
        log.warning("Problem with opening file %s: %s", config_file, e)
    return config 
Example 11
Project: dagster   Author: dagster-io   File: pypirc.py    License: Apache License 2.0 6 votes vote down vote up
def get_repository_config(self, repository):
        """Get config dictionary for the given repository.

        If the repository section is not found in the config file,
        return ``None``.  If the file is invalid, raise
        :exc:`configparser.Error`.

        Otherwise return a dictionary with:

        * ``'repository'`` -- the repository URL
        * ``'username'`` -- username for authentication
        * ``'password'`` -- password for authentication

        :param repository:
            Name or URL of the repository to find in the ``.pypirc`` file.
            The repository section must be defined in the config file.

        """
        servers = self._read_index_servers()
        repo_config = self._find_repo_config(servers, repository)
        return repo_config 
Example 12
Project: oslo.log   Author: openstack   File: log.py    License: Apache License 2.0 6 votes vote down vote up
def _load_log_config(log_config_append):
    try:
        if not hasattr(_load_log_config, "old_time"):
            _load_log_config.old_time = 0
        new_time = os.path.getmtime(log_config_append)
        if _load_log_config.old_time != new_time:
            # Reset all existing loggers before reloading config as fileConfig
            # does not reset non-child loggers.
            for logger in _iter_loggers():
                logger.setLevel(logging.NOTSET)
                logger.handlers = []
                logger.propagate = 1
            logging.config.fileConfig(log_config_append,
                                      disable_existing_loggers=False)
            _load_log_config.old_time = new_time
    except (configparser.Error, KeyError, os.error) as exc:
        raise LogConfigError(log_config_append, str(exc)) 
Example 13
Project: komodo-wakatime   Author: wakatime   File: configs.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def parseConfigFile(configFile=None):
    """Returns a configparser.SafeConfigParser instance with configs
    read from the config file. Default location of the config file is
    at ~/.wakatime.cfg.
    """

    # get config file location from ENV
    if not configFile:
        configFile = getConfigFile()

    configs = configparser.ConfigParser(delimiters=('='), strict=False)
    try:
        with open(configFile, 'r', encoding='utf-8') as fh:
            try:
                configs.read_file(fh)
            except configparser.Error:
                print(traceback.format_exc())
                raise SystemExit(CONFIG_FILE_PARSE_ERROR)
    except IOError:
        pass
    return configs 
Example 14
Project: zbxdb   Author: ikzelf   File: zbxdb.py    License: GNU General Public License v3.0 5 votes vote down vote up
def setup_logging(
        default_path='etc/logging.json',
        default_level=logging.INFO,
        env_key='LOG_CFG'
):
    """Setup logging configuration

    """
    path = default_path
    value = os.getenv(env_key, None)

    if value:
        path = value

    if os.path.exists(path):
        with open(path, 'rt') as _f:
            config = json.load(_f)
            try:
                logging.config.dictConfig(config)
            except ValueError as _e:
                print("Error during reading log configuration")
                print(config)
                print("Does the path for filename exist?")
                raise

            return path
    print("Falling back to default logging config")
    logging.basicConfig(level=default_level)

    return False 
Example 15
Project: qutebrowser   Author: qutebrowser   File: configfiles.py    License: GNU General Public License v3.0 5 votes vote down vote up
def bind(self, key: str,
             command: typing.Optional[str],
             mode: str = 'normal') -> None:
        """Bind a key to a command, with an optional key mode."""
        with self._handle_error('binding', key):
            seq = keyutils.KeySequence.parse(key)
            if command is None:
                raise configexc.Error("Can't bind {key} to None (maybe you "
                                      "want to use config.unbind('{key}') "
                                      "instead?)".format(key=key))
            self._keyconfig.bind(seq, command, mode=mode) 
Example 16
Project: qutebrowser   Author: qutebrowser   File: configfiles.py    License: GNU General Public License v3.0 5 votes vote down vote up
def read_autoconfig() -> None:
    """Read the autoconfig.yml file."""
    try:
        config.instance.read_yaml()
    except configexc.ConfigFileErrors:
        raise  # caught in outer block
    except configexc.Error as e:
        desc = configexc.ConfigErrorDesc("Error", e)
        raise configexc.ConfigFileErrors('autoconfig.yml', [desc]) 
Example 17
Project: Watson   Author: TailorDev   File: watson.py    License: MIT License 5 votes vote down vote up
def config(self):
        """
        Return Watson's config as a ConfigParser object.
        """
        if not self._config:
            try:
                config = ConfigParser()
                config.read(self.config_file)
            except configparser.Error as e:
                raise ConfigurationError(
                    u"Cannot parse config file: {}".format(e))

            self._config = config

        return self._config 
Example 18
Project: MatchingMarkets.py   Author: QuantEcon   File: solvers.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def objSa(self, vars = None):
            """Objective coefficient sensitivity analysis.

            Called after a problem has been solved, this function
            returns a dict mapping variables to pairs (lo, hi) indicating
            that the objective coefficient of the variable can vary
            between lo and hi without changing the optimal basis
            (if other coefficients remain constant).  If an iterable
            vars is given, results are returned only for variables in vars.
            """
            if vars is None:
                v2n = self.v2n
            else:
                v2n = dict((v, self.v2n[v]) for v in vars)
            ifirst = min(v2n.values())
            ilast = max(v2n.values())

            row_t = ctypes.c_double * (ilast - ifirst + 1)
            lo = row_t()
            hi = row_t()
            status = ctypes.c_int()
            status.value = CPLEX_DLL.lib.CPXobjsa(self.env, self.hprob,
                                                  ifirst, ilast, lo, hi)
            if status.value != 0:
                raise PulpSolverError("Error in CPXobjsa, status="
                                        + str(status))
            return dict((v, (lo[i - ifirst], hi[i - ifirst]))
                        for v, i in v2n.items()) 
Example 19
Project: vcm   Author: willasaywhat   File: vcm.py    License: GNU General Public License v3.0 5 votes vote down vote up
def create_folder(folder):
    if not os.path.exists(folder):
        try:
            os.makedirs(folder)
        except OSError as ex:
            print(f"Error creating folder: {folder} : {ex.strerror}")
            return 
Example 20
Project: vcm   Author: willasaywhat   File: vcm.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testssl():
    try:
        project_config = VcmProjectConfig()
        project_config.read_project_vcm()
    except ValueError as ex:
        print(ex)
        return

    https_targets = []
    for t in project_config.targets:
        https_targets.append('https://' + urlparse(t).netloc)

    if not click.confirm('Run testssl against the following targets: %s' % ', '.join(https_targets)):
        return

    for t in https_targets:
        output_filename = os.path.join(project_config.artifacts_folder, f"testssl_{urlparse(t).netloc}_{time.time()}.txt")

        try:
            args = ["testssl.sh", "--openssl", global_config.open_ssl_binary, "--logfile", output_filename, t]

            print(args)
            call(args)

        except Exception as ex:
            print(f"Error writing testssl output to: {output_filename} : {ex}") 
Example 21
Project: vanguards   Author: mikeperry-tor   File: config.py    License: MIT License 5 votes vote down vote up
def get_option(config, section, option, default):
  try:
    if type(default) == bool:
      ret = config.get(section, option) == "True"
    else:
      ret = type(default)(config.get(section, option))
  except Error as e:
    return default
  return ret 
Example 22
Project: clusterfuzz   Author: google   File: options.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, options_file_path, cwd=None):
    if not os.path.exists(options_file_path):
      raise FuzzerOptionsException('fuzzer options file does not exist.')

    if cwd:
      self._cwd = cwd
    else:
      self._cwd = os.path.dirname(options_file_path)

    self._config = configparser.ConfigParser()
    with open(options_file_path, 'r') as f:
      try:
        self._config.read_file(f)
      except configparser.Error:
        raise FuzzerOptionsException('Failed to parse fuzzer options file.') 
Example 23
Project: neutron-vpnaas   Author: openstack   File: netns_wrapper.py    License: Apache License 2.0 5 votes vote down vote up
def filter_command(command, rootwrap_config):
    # Load rootwrap configuration
    try:
        rawconfig = ConfigParser.RawConfigParser()
        rawconfig.read(rootwrap_config)
        rw_config = wrapper.RootwrapConfig(rawconfig)
    except ValueError as exc:
        LOG.error('Incorrect value in %(config)s: %(exc)s',
                  {'config': rootwrap_config, 'exc': exc})
        sys.exit(errno.EINVAL)
    except ConfigParser.Error:
        LOG.error('Incorrect configuration file: %(config)s',
                  {'config': rootwrap_config})
        sys.exit(errno.EINVAL)

    # Check if command matches any of the loaded filters
    filters = wrapper.load_filters(rw_config.filters_path)
    try:
        wrapper.match_filter(filters, command, exec_dirs=rw_config.exec_dirs)
    except wrapper.FilterMatchNotExecutable as exc:
        LOG.error('Command %(command)s is not executable: '
                  '%(path)s (filter match = %(name)s)',
                  {'command': command,
                   'path': exc.match.exec_path,
                   'name': exc.match.name})
        sys.exit(errno.EINVAL)
    except wrapper.NoFilterMatched:
        LOG.error('Unauthorized command: %(cmd)s (no filter matched)',
                  {'cmd': command})
        sys.exit(errno.EPERM) 
Example 24
Project: pyx   Author: pyx-project   File: config.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get(section, option, default=_marker):
    if default is _marker:
        return config.get(section, option)
    else:
        try:
            return config.get(section, option)
        except configparser.Error:
            return default 
Example 25
Project: pyx   Author: pyx-project   File: config.py    License: GNU General Public License v2.0 5 votes vote down vote up
def getint(section, option, default=_marker):
    if default is _marker:
        return config.getint(section, option)
    else:
        try:
            return config.getint(section, option)
        except configparser.Error:
            return default 
Example 26
Project: pyx   Author: pyx-project   File: config.py    License: GNU General Public License v2.0 5 votes vote down vote up
def getfloat(section, option, default=_marker):
    if default is _marker:
        return config.getfloat(section, option)
    else:
        try:
            return config.getfloat(section, option)
        except configparser.Error:
            return default 
Example 27
Project: pyx   Author: pyx-project   File: config.py    License: GNU General Public License v2.0 5 votes vote down vote up
def getboolean(section, option, default=_marker):
    if default is _marker:
        return config.getboolean(section, option)
    else:
        try:
            return config.getboolean(section, option)
        except configparser.Error:
            return default 
Example 28
Project: pyx   Author: pyx-project   File: config.py    License: GNU General Public License v2.0 5 votes vote down vote up
def getlist(section, option, default=_marker):
    if default is _marker:
        l = config.get(section, option).split()
    else:
        try:
            l = config.get(section, option).split()
        except configparser.Error:
            return default
    if space:
        l = [item.replace(space, " ") for item in l]
    return l 
Example 29
Project: eyeD3   Author: nicfit   File: main.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _loadConfig(args):
    config_files = []

    if args.config:
        config_files.append(os.path.abspath(args.config))

    if args.no_config is False:
        config_files.append(DEFAULT_CONFIG)
        config_files.append(DEFAULT_CONFIG_DEPRECATED)

    if not config_files:
        return None

    for config_file in config_files:
        if os.path.isfile(config_file):
            _deprecatedConfigFileCheck(config_file)

            try:
                config = ConfigParser()
                config.read(config_file)
            except ConfigParserError as ex:
                eyed3.log.warning(f"User config error: {ex}")
                return None
            else:
                return config
        elif config_file != DEFAULT_CONFIG and config_file != DEFAULT_CONFIG_DEPRECATED:
            raise IOError(f"User config not found: {config_file}") 
Example 30
Project: silvia-pi   Author: brycesub   File: bottle.py    License: MIT License 5 votes vote down vote up
def wsgi(self, environ, start_response):
        """ The bottle WSGI-interface. """
        try:
            out = self._cast(self._handle(environ))
            # rfc2616 section 4.3
            if response._status_code in (100, 101, 204, 304)\
            or environ['REQUEST_METHOD'] == 'HEAD':
                if hasattr(out, 'close'): out.close()
                out = []
            start_response(response._status_line, response.headerlist)
            return out
        except (KeyboardInterrupt, SystemExit, MemoryError):
            raise
        except Exception as E:
            if not self.catchall: raise
            err = '<h1>Critical error while processing request: %s</h1>' \
                  % html_escape(environ.get('PATH_INFO', '/'))
            if DEBUG:
                err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \
                       '<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \
                       % (html_escape(repr(E)), html_escape(format_exc()))
            environ['wsgi.errors'].write(err)
            environ['wsgi.errors'].flush()
            headers = [('Content-Type', 'text/html; charset=UTF-8')]
            start_response('500 INTERNAL SERVER ERROR', headers, sys.exc_info())
            return [tob(err)]