Python configparser.Error() Examples

The following are 30 code examples of configparser.Error(). 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 configparser , or try the search function .
Example #1
Source File: configfiles.py    From qutebrowser with 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
Source File: vcm.py    From vcm with 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 #3
Source File: vcm.py    From vcm with 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 #4
Source File: vcm.py    From vcm with 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
Source File: config.py    From twtxt with 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 #6
Source File: pypirc.py    From dagster with 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 #7
Source File: log.py    From oslo.log with 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 #8
Source File: solvers.py    From MatchingMarkets.py with 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 #9
Source File: config.py    From gtg with 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 #10
Source File: yum.py    From atomic-reactor with 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 #11
Source File: application.py    From gtg with 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 #12
Source File: configs.py    From komodo-wakatime with 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 #13
Source File: configfiles.py    From qutebrowser with 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 #14
Source File: utils.py    From bandit with Apache License 2.0 5 votes vote down vote up
def parse_ini_file(f_loc):
    config = configparser.ConfigParser()
    try:
        config.read(f_loc)
        return {k: v for k, v in config.items('bandit')}

    except (configparser.Error, KeyError, TypeError):
        LOG.warning("Unable to parse config file %s or missing [bandit] "
                    "section", f_loc)

    return None 
Example #15
Source File: matrix_bridge.py    From python-zulip-api with Apache License 2.0 5 votes vote down vote up
def read_configuration(config_file: str) -> Dict[str, Dict[str, str]]:
    config = configparser.ConfigParser()

    try:
        config.read(config_file)
    except configparser.Error as exception:
        raise Bridge_ConfigException(str(exception))

    if set(config.sections()) != {'matrix', 'zulip'}:
        raise Bridge_ConfigException("Please ensure the configuration has zulip & matrix sections.")

    # TODO Could add more checks for configuration content here

    return {section: dict(config[section]) for section in config.sections()} 
Example #16
Source File: test_configparser.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_error(self):
        import pickle
        e1 = configparser.Error('value')
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            pickled = pickle.dumps(e1, proto)
            e2 = pickle.loads(pickled)
            self.assertEqual(e1.message, e2.message)
            self.assertEqual(repr(e1), repr(e2)) 
Example #17
Source File: matrix_bridge.py    From python-zulip-api with Apache License 2.0 5 votes vote down vote up
def write_sample_config(target_path: str, zuliprc: Optional[str]) -> None:
    if os.path.exists(target_path):
        raise Bridge_ConfigException("Path '{}' exists; not overwriting existing file.".format(target_path))

    sample_dict = OrderedDict((
        ('matrix', OrderedDict((
            ('host', 'https://matrix.org'),
            ('username', 'username'),
            ('password', 'password'),
            ('room_id', '#zulip:matrix.org'),
        ))),
        ('zulip', OrderedDict((
            ('email', 'glitch-bot@chat.zulip.org'),
            ('api_key', 'aPiKeY'),
            ('site', 'https://chat.zulip.org'),
            ('stream', 'test here'),
            ('topic', 'matrix'),
        ))),
    ))

    if zuliprc is not None:
        if not os.path.exists(zuliprc):
            raise Bridge_ConfigException("Zuliprc file '{}' does not exist.".format(zuliprc))

        zuliprc_config = configparser.ConfigParser()
        try:
            zuliprc_config.read(zuliprc)
        except configparser.Error as exception:
            raise Bridge_ConfigException(str(exception))

        # Can add more checks for validity of zuliprc file here

        sample_dict['zulip']['email'] = zuliprc_config['api']['email']
        sample_dict['zulip']['site'] = zuliprc_config['api']['site']
        sample_dict['zulip']['api_key'] = zuliprc_config['api']['key']

    sample = configparser.ConfigParser()
    sample.read_dict(sample_dict)
    with open(target_path, 'w') as target:
        sample.write(target) 
Example #18
Source File: config.py    From recipy with Apache License 2.0 5 votes vote down vote up
def get_gui_port():
    try:
        return int(conf.get('general', 'port'))
    except Error:
        return 9000 
Example #19
Source File: test_configparser.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_interpolation_missing_value(self):
        cf = self.get_interpolation_config()
        e = self.get_error(cf, configparser.InterpolationMissingOptionError,
                           "Interpolation Error", "name")
        self.assertEqual(e.reference, "reference")
        self.assertEqual(e.section, "Interpolation Error")
        self.assertEqual(e.option, "name")
        if self.interpolation == configparser._UNSET:
            self.assertEqual(e.args, ('name', 'Interpolation Error',
                                    '%(reference)s', 'reference'))
        elif isinstance(self.interpolation, configparser.LegacyInterpolation):
            self.assertEqual(e.args, ('name', 'Interpolation Error',
                                    '%(reference)s', 'reference')) 
Example #20
Source File: lib.py    From python-zulip-api with Apache License 2.0 5 votes vote down vote up
def put(self, key: Text, value: Any) -> None:
        self.state_[key] = self.marshal(value)
        response = self._client.update_storage({'storage': {key: self.state_[key]}})
        if response['result'] != 'success':
            raise StateHandlerError("Error updating state: {}".format(str(response))) 
Example #21
Source File: test_configparser.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def get_interpolation_config(self):
        return self.fromstring(
            "[Foo]\n"
            "bar{equals}something %(with1)s interpolation (1 step)\n"
            "bar9{equals}something %(with9)s lots of interpolation (9 steps)\n"
            "bar10{equals}something %(with10)s lots of interpolation (10 steps)\n"
            "bar11{equals}something %(with11)s lots of interpolation (11 steps)\n"
            "with11{equals}%(with10)s\n"
            "with10{equals}%(with9)s\n"
            "with9{equals}%(with8)s\n"
            "with8{equals}%(With7)s\n"
            "with7{equals}%(WITH6)s\n"
            "with6{equals}%(with5)s\n"
            "With5{equals}%(with4)s\n"
            "WITH4{equals}%(with3)s\n"
            "with3{equals}%(with2)s\n"
            "with2{equals}%(with1)s\n"
            "with1{equals}with\n"
            "\n"
            "[Mutual Recursion]\n"
            "foo{equals}%(bar)s\n"
            "bar{equals}%(foo)s\n"
            "\n"
            "[Interpolation Error]\n"
            # no definition for 'reference'
            "name{equals}%(reference)s\n".format(equals=self.delimiters[0])) 
Example #22
Source File: snipsTools.py    From snips-app-template-py with MIT License 5 votes vote down vote up
def write_configuration_file(configuration_file, data):
        conf_parser = SnipsConfigParser()
        for key in data.keys():
            conf_parser.add_section(key)
            for inner_key in data[key].keys():
                conf_parser.set(key, inner_key, data[key][inner_key])

        try:
            with open(configuration_file, 'w') as f:
                conf_parser.write(f)
                return True

        except (IOError, configparser.Error) as e:
            print(e)
            return False 
Example #23
Source File: snipsTools.py    From snips-app-template-py with MIT License 5 votes vote down vote up
def read_configuration_file(configuration_file):
        try:
            with io.open(
                    configuration_file,
                    encoding=CONFIGURATION_ENCODING_FORMAT) as f:

                conf_parser = SnipsConfigParser()
                conf_parser.readfp(f)
                return conf_parser.to_dict()

        except (IOError, configparser.Error) as e:
            print(e)
            return dict() 
Example #24
Source File: config.py    From pytos with Apache License 2.0 5 votes vote down vote up
def _read_config_files(self):
        try:
            self.read(self.config_file_path)
        except configparser.Error as config_exception:
            logger.error("Could not parse configuration file '%s'.", self.config_file_path)
            raise config_exception

        if self.custom_config_file_path is not None:
            try:
                self.read(self.custom_config_file_path)
            except configparser.Error:
                logger.error("Could not parse custom configuration file '%s'.", self.custom_config_file_path) 
Example #25
Source File: test_config.py    From gtg with GNU General Public License v3.0 5 votes vote down vote up
def test_falls_back_when_there_is_config_error(self, mock_log):
        self.mock_parser.side_effect = configparser.Error()
        open_config_file('gtg.conf')
        self.mock_parser.assert_called_once_with('gtg.conf')
        self.assertTrue(mock_log.warning.called) 
Example #26
Source File: application.py    From gtg with GNU General Public License v3.0 5 votes vote down vote up
def open_help(self, action, param):
        """Open help callback."""

        try:
            Gtk.show_uri(None, "help:gtg", Gdk.CURRENT_TIME)
        except GLib.Error:
            log.error('Could not open help') 
Example #27
Source File: RecipeReader.py    From civet with Apache License 2.0 5 votes vote down vote up
def __init__(self, recipe_dir, filename):
        """
        Constructor.
        Input:
          recipe_dir: str: Path to the recipe repo
          filename: .cfg file to read
        """
        self.recipe_dir = recipe_dir
        self.filename = filename
        self.hardcoded_sections = [
                "Main",
                "Global Sources",
                "PullRequest Dependencies",
                "Push Dependencies",
                "Manual Dependencies",
                "Release Dependencies",
                "Global Environment",
                ]
        self.config = configparser.RawConfigParser()
        # ConfigParser will default to having case insensitive options and
        # returning lower case versions of options. This is not good
        # for environment variables
        self.config.optionxform = str

        fname = os.path.join(recipe_dir, filename)
        valid_files = self.config.read([fname])
        if not valid_files:
            raise configparser.Error("Bad filename: %s" % fname)
        self.recipe = {} 
Example #28
Source File: config.py    From ArtStationDownloader with MIT License 5 votes vote down vote up
def write_config(config_file_path, field, key, value):
    cf = configparser.ConfigParser()
    try:
        cf.read(config_file_path)
        if field not in cf:
            cf.add_section(field)
        cf[field][key] = value
        cf.write(open(config_file_path, 'w'))
    except configparser.Error as e:
        print(e)
        return False
    return True 
Example #29
Source File: config.py    From ArtStationDownloader with MIT License 5 votes vote down vote up
def read_config(config_file_path, field, key):
    cf = configparser.ConfigParser()
    try:
        cf.read(config_file_path)
        if field in cf:
            result = cf[field][key]
        else:
            return ''
    except configparser.Error as e:
        print(e)
        return ''
    return result 
Example #30
Source File: config.py    From recipy with Apache License 2.0 5 votes vote down vote up
def get_db_path():
    try:
        return conf.get('database', 'path')
    except Error:
        return os.path.expanduser('~/.recipy/recipyDB.json')