Python six.moves.configparser.NoSectionError() Examples

The following are 20 code examples of six.moves.configparser.NoSectionError(). 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 six.moves.configparser , or try the search function .
Example #1
Source File: __main__.py    From profiling with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def config_flag(option, value, default=False, section=cli.name):
    """Guesses whether a CLI flag should be turned on or off from the
    configuration.  If the configuration option value is same with the given
    value, it returns ``True``.

    ::

       @click.option('--ko-kr', 'locale', is_flag=True,
                     default=config_flag('locale', 'ko_KR'))

    """
    class x(object):
        def __bool__(self, option=option, value=value,
                     default=default, section=section):
            config = read_config()
            type = builtins.type(value)
            get_option = option_getter(type)
            try:
                return get_option(config, section, option) == value
            except (NoOptionError, NoSectionError):
                return default
        __nonzero__ = __bool__
    return x() 
Example #2
Source File: tooling2.py    From vscode-azurecli with MIT License 6 votes vote down vote up
def get_configured_defaults():
    config = _reload_config()
    try:
        defaults_section = config.defaults_section_name if hasattr(config, 'defaults_section_name') else 'defaults'
        defaults = {}
        if before_2_0_64:
            options = config.config_parser.options(defaults_section)
            for opt in options:
                value = config.get(defaults_section, opt)
                if value:
                    defaults[opt] = value
        else:
            options = config.items(defaults_section)
            for opt in options:
                name = opt['name']
                value = opt['value']
                if value:
                    defaults[name] = value
        return defaults
    except configparser.NoSectionError:
        return {} 
Example #3
Source File: cli.py    From mygeotab-python with Apache License 2.0 6 votes vote down vote up
def load(self, name=None):
        config = configparser.ConfigParser()
        config.read(self._get_config_file())
        try:
            if name is None:
                sections = config.sections()
                if len(sections) < 1:
                    self.credentials = None
                    return
                section_name = sections[-1]
            else:
                section_name = self._section_name(name)
            username = config.get(section_name, "username")
            session_id = config.get(section_name, "session_id")
            database = config.get(section_name, "database")
            server = config.get(section_name, "server")
            self.credentials = mygeotab.Credentials(username, session_id, database, server)
        except configparser.NoSectionError:
            self.credentials = None
        except configparser.NoOptionError:
            self.credentials = None 
Example #4
Source File: kojibuild.py    From rdopkg with Apache License 2.0 6 votes vote down vote up
def new_build(watch=True):
    modules_check()
    flog = setup_fedpkg_logger()  # NOQA
    fcmd = get_fedpkg_commands()
    task_id = fcmd.build()

    if watch:
        print('')
        try:
            cli = get_fedpkg_cli()
            # TODO: might be good to push this return data back up
            #       or check the status of the return
            r = cli._watch_koji_tasks(fcmd.kojisession, [task_id])
        except configparser.NoSectionError:
            # <C-C> causes this for some reason
            print('')
        except Exception as ex:
            log.warn(str(type(ex).__name__))
            log.warn("Failed to get build status: %s" % ex)

    return fcmd.nvr 
Example #5
Source File: __main__.py    From profiling with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def config_default(option, default=None, type=None, section=cli.name):
    """Guesses a default value of a CLI option from the configuration.

    ::

       @click.option('--locale', default=config_default('locale'))

    """
    def f(option=option, default=default, type=type, section=section):
        config = read_config()
        if type is None and default is not None:
            # detect type from default.
            type = builtins.type(default)
        get_option = option_getter(type)
        try:
            return get_option(config, section, option)
        except (NoOptionError, NoSectionError):
            return default
    return f 
Example #6
Source File: pip.py    From stash with MIT License 5 votes vote down vote up
def _get_section_name(self, name):
        for section_name in self.sections():
            if section_name.lower() == name.lower():
                return section_name
        else:
            raise NoSectionError(name) 
Example #7
Source File: app.py    From azure-cli-shell with MIT License 5 votes vote down vote up
def _update_default_info(self):
        try:
            options = az_config.config_parser.options(DEFAULTS_SECTION)
            self.config_default = ""
            for opt in options:
                self.config_default += opt + ": " + az_config.get(DEFAULTS_SECTION, opt) + "  "
        except configparser.NoSectionError:
            self.config_default = "" 
Example #8
Source File: cw_base.py    From pycoast with GNU General Public License v3.0 5 votes vote down vote up
def _config_to_dict(self, config_file):
        """Convert a config file to a dict."""
        config = configparser.ConfigParser()
        try:
            with open(config_file, 'r'):
                logger.info("Overlays config file %s found", str(config_file))
            config.read(config_file)
        except IOError:
            logger.error("Overlays config file %s does not exist!",
                         str(config_file))
            raise
        except configparser.NoSectionError:
            logger.error("Error in %s", str(config_file))
            raise

        SECTIONS = ['cache', 'coasts', 'rivers', 'borders', 'cities', 'points', 'grid']
        overlays = {}
        for section in config.sections():
            if section in SECTIONS:
                overlays[section] = {}
                for option in config.options(section):
                    val = config.get(section, option)
                    try:
                        overlays[section][option] = ast.literal_eval(val)
                    except ValueError:
                        overlays[section][option] = val
        return overlays 
Example #9
Source File: config.py    From heat-translator with Apache License 2.0 5 votes vote down vote up
def get_value(cls, section, key):
        try:
            value = cls._translator_config.get(section, key)
        except configparser.NoOptionError:
            raise exception.ConfOptionNotDefined(key=key, section=section)
        except configparser.NoSectionError:
            raise exception.ConfSectionNotDefined(section=section)

        return value 
Example #10
Source File: credential_store.py    From azure-devops-cli-extension with MIT License 5 votes vote down vote up
def get_PAT_from_file(self, key):
        ensure_dir(AZ_DEVOPS_GLOBAL_CONFIG_DIR)
        logger.debug('Keyring not configured properly or package not found.'
                     'Looking for credentials with key:%s in the file: %s', key, self._PAT_FILE)
        creds_list = self._get_credentials_list()
        try:
            return creds_list.get(key, self._USERNAME)
        except (configparser.NoOptionError, configparser.NoSectionError):
            return None 
Example #11
Source File: __main__.py    From c4ddev with MIT License 5 votes vote down vote up
def projecttool(args, get_path, set_path):
  """
  Run the MAXON API Project Tool. The path to the project tool must be
  configured once.
  """

  cfg = load_cfg()
  if set_path:
    if not os.path.isfile(set_path):
      print('fatal: "{}" is not a file'.format(set_path), file=sys.stderr)
      sys.exit(2)
    if not cfg.has_section('projecttool'):
      cfg.add_section('projecttool')
    cfg.set('projecttool', 'path', set_path)
    save_cfg(cfg)
    return
  try:
    path = cfg.get('projecttool', 'path')
  except NoSectionError:
    print('fatal: path to projecttool is not configured', file=sys.stderr)
    sys.exit(1)
  if get_path:
    print(path)
    return

  sys.exit(oscall([path] + list(args))) 
Example #12
Source File: tooling2.py    From vscode-azurecli with MIT License 5 votes vote down vote up
def _find_configured_default(config, argument):
    if not (hasattr(argument.type, 'default_name_tooling') and argument.type.default_name_tooling):
        return None
    try:
        defaults_section = config.defaults_section_name if hasattr(config, 'defaults_section_name') else 'defaults'
        return config.get(defaults_section, argument.type.default_name_tooling, None)
    except configparser.NoSectionError:
        return None 
Example #13
Source File: tooling1.py    From vscode-azurecli with MIT License 5 votes vote down vote up
def get_configured_defaults():
    _reload_config()
    try:
        options = az_config.config_parser.options(DEFAULTS_SECTION)
        defaults = {}
        for opt in options:
            value = az_config.get(DEFAULTS_SECTION, opt)
            if value:
                defaults[opt] = value
        return defaults
    except configparser.NoSectionError:
        return {} 
Example #14
Source File: tooling1.py    From vscode-azurecli with MIT License 5 votes vote down vote up
def _find_configured_default(argument):
    if not (hasattr(argument.type, 'default_name_tooling') and argument.type.default_name_tooling):
        return None
    try:
        return az_config.get(DEFAULTS_SECTION, argument.type.default_name_tooling, None)
    except configparser.NoSectionError:
        return None 
Example #15
Source File: base.py    From pycbc with GNU General Public License v3.0 5 votes vote down vote up
def from_config(cls, cp, variable_params):
        """Gets sampling transforms specified in a config file.

        Sampling parameters and the parameters they replace are read from the
        ``sampling_params`` section, if it exists. Sampling transforms are
        read from the ``sampling_transforms`` section(s), using
        ``transforms.read_transforms_from_config``.

        An ``AssertionError`` is raised if no ``sampling_params`` section
        exists in the config file.

        Parameters
        ----------
        cp : WorkflowConfigParser
            Config file parser to read.
        variable_params : list
            List of parameter names of the original variable params.

        Returns
        -------
        SamplingTransforms
            A sampling transforms class.
        """
        # Check if a sampling_params section is provided
        try:
            sampling_params, replace_parameters = \
                read_sampling_params_from_config(cp)
        except NoSectionError as e:
            logging.warning("No sampling_params section read from config file")
            raise e
        # get sampling transformations
        sampling_transforms = transforms.read_transforms_from_config(
            cp, 'sampling_transforms')
        logging.info("Sampling in {} in place of {}".format(
            ', '.join(sampling_params), ', '.join(replace_parameters)))
        return cls(variable_params, sampling_params,
                   replace_parameters, sampling_transforms) 
Example #16
Source File: configparser.py    From platoon with MIT License 5 votes vote down vote up
def fetch_devices_for_host(host):
    """A successful search returns a list of theano devices' string values.
    An unsuccessful search raises a KeyError.

    The (decreasing) priority order is:
    - PLATOON_DEVICES
    - PLATOONRC files (if they exist) from right to left
    - working directory's ./.platoonrc
    - ~/.platoonrc

    """
    # first try to have PLATOON_DEVICES
    if PLATOON_DEVICES:
        splitter = shlex.shlex(PLATOON_DEVICES, posix=True)
        splitter.whitespace += ','
        splitter.whitespace_split = True
        return list(splitter)

    # next try to find it in the config file
    try:
        try:
            devices = platoon_cfg.get("devices", host)
        except ConfigParser.InterpolationError:
            devices = platoon_raw_cfg.get("devices", host)
    except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
        raise KeyError(host)
    splitter = shlex.shlex(devices, posix=True)
    splitter.whitespace += ','
    splitter.whitespace_split = True
    return list(splitter) 
Example #17
Source File: configparser.py    From platoon with MIT License 5 votes vote down vote up
def fetch_hosts():
    """A successful search returns a list of host to participate in a multi-node
    platoon. An unsuccessful search raises a KeyError.

    The (decreasing) priority order is:
    - PLATOON_HOSTS
    - PLATOONRC files (if they exist) from right to left
    - working directory's ./.platoonrc
    - ~/.platoonrc

    """
    # first try to have PLATOON_HOSTS
    if PLATOON_HOSTS:
        splitter = shlex.shlex(PLATOON_HOSTS, posix=True)
        splitter.whitespace += ','
        splitter.whitespace_split = True
        return list(splitter)

    # next try to find it in the config file
    try:
        try:
            hosts = platoon_cfg.get("platoon", "hosts")
        except ConfigParser.InterpolationError:
            hosts = platoon_raw_cfg.get("platoon", "hosts")
    except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
        raise KeyError("hosts")
    splitter = shlex.shlex(hosts, posix=True)
    splitter.whitespace += ','
    splitter.whitespace_split = True
    return list(splitter) 
Example #18
Source File: peer.py    From sydent with Apache License 2.0 4 votes vote down vote up
def __init__(self, sydent, server_name, port, pubkeys, lastSentVersion):
        """
        :param sydent: The current Sydent instance.
        :type sydent: sydent.sydent.Sydent
        :param server_name: The peer's server name.
        :type server_name: unicode
        :param port: The peer's port.
        :type port: int
        :param pubkeys: The peer's public keys in a dict[key_id, key_b64]
        :type pubkeys: dict[unicode, unicode]
        :param lastSentVersion: The ID of the last association sent to the peer.
        :type lastSentVersion: int
        """
        super(RemotePeer, self).__init__(server_name, pubkeys)
        self.sydent = sydent
        self.port = port
        self.lastSentVersion = lastSentVersion

        # look up or build the replication URL
        try:
            replication_url = sydent.cfg.get(
                "peer.%s" % server_name, "base_replication_url",
            )
        except (configparser.NoSectionError, configparser.NoOptionError):
            if not port:
                port = 1001
            replication_url = "https://%s:%i" % (server_name, port)

        if replication_url[-1:] != '/':
            replication_url += "/"

        replication_url += "_matrix/identity/replicate/v1/push"
        self.replication_url = replication_url

        # Get verify key for this peer

        # Check if their key is base64 or hex encoded
        pubkey = self.pubkeys[SIGNING_KEY_ALGORITHM]
        try:
            # Check for hex encoding
            int(pubkey, 16)

            # Decode hex into bytes
            pubkey_decoded = binascii.unhexlify(pubkey)

            logger.warn("Peer public key of %s is hex encoded. Please update to base64 encoding", server_name)
        except ValueError:
            # Check for base64 encoding
            try:
                pubkey_decoded = decode_base64(pubkey)
            except Exception as e:
                raise ConfigError(
                    "Unable to decode public key for peer %s: %s" % (server_name, e),
                )

        self.verify_key = signedjson.key.decode_verify_key_bytes(SIGNING_KEY_ALGORITHM + ":", pubkey_decoded)

        # Attach metadata
        self.verify_key.alg = SIGNING_KEY_ALGORITHM
        self.verify_key.version = 0 
Example #19
Source File: main.py    From doc8 with Apache License 2.0 4 votes vote down vote up
def extract_config(args):
    parser = configparser.RawConfigParser()
    read_files = []
    if args["config"]:
        for fn in args["config"]:
            with open(fn, "r") as fh:
                parser.readfp(fh, filename=fn)
                read_files.append(fn)
    else:
        read_files.extend(parser.read(CONFIG_FILENAMES))
    if not read_files:
        return {}
    cfg = {}
    try:
        cfg["max_line_length"] = parser.getint("doc8", "max-line-length")
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    try:
        cfg["ignore"] = split_set_type(parser.get("doc8", "ignore"))
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    try:
        cfg["ignore_path"] = split_set_type(parser.get("doc8", "ignore-path"))
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    try:
        ignore_path_errors = parser.get("doc8", "ignore-path-errors")
        ignore_path_errors = split_set_type(ignore_path_errors)
        ignore_path_errors = parse_ignore_path_errors(ignore_path_errors)
        cfg["ignore_path_errors"] = ignore_path_errors
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    try:
        cfg["allow_long_titles"] = parser.getboolean("doc8", "allow-long-titles")
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    try:
        cfg["sphinx"] = parser.getboolean("doc8", "sphinx")
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    try:
        cfg["verbose"] = parser.getboolean("doc8", "verbose")
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    try:
        cfg["file_encoding"] = parser.get("doc8", "file-encoding")
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    try:
        cfg["default_extension"] = parser.get("doc8", "default-extension")
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    try:
        extensions = parser.get("doc8", "extensions")
        extensions = extensions.split(",")
        extensions = [s.strip() for s in extensions if s.strip()]
        if extensions:
            cfg["extension"] = extensions
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    return cfg 
Example #20
Source File: base.py    From pycbc with GNU General Public License v3.0 4 votes vote down vote up
def _init_args_from_config(cls, cp):
        """Helper function for loading parameters.

        This retrieves the prior, variable parameters, static parameterss,
        constraints, sampling transforms, and waveform transforms
        (if provided).

        Parameters
        ----------
        cp : ConfigParser
            Config parser to read.

        Returns
        -------
        dict :
            Dictionary of the arguments. Has keys ``variable_params``,
            ``static_params``, ``prior``, and ``sampling_transforms``. If
            waveform transforms are in the config file, will also have
            ``waveform_transforms``.
        """
        section = "model"
        prior_section = "prior"
        vparams_section = 'variable_params'
        sparams_section = 'static_params'
        constraint_section = 'constraint'
        # check that the name exists and matches
        name = cp.get(section, 'name')
        if name != cls.name:
            raise ValueError("section's {} name does not match mine {}".format(
                             name, cls.name))
        # get model parameters
        variable_params, static_params = distributions.read_params_from_config(
            cp, prior_section=prior_section, vargs_section=vparams_section,
            sargs_section=sparams_section)
        # get prior
        prior = cls.prior_from_config(cp, variable_params, prior_section,
                                      constraint_section)
        args = {'variable_params': variable_params,
                'static_params': static_params,
                'prior': prior}
        # try to load sampling transforms
        try:
            sampling_transforms = SamplingTransforms.from_config(
                cp, variable_params)
        except NoSectionError:
            sampling_transforms = None
        args['sampling_transforms'] = sampling_transforms
        # get any waveform transforms
        if any(cp.get_subsections('waveform_transforms')):
            logging.info("Loading waveform transforms")
            args['waveform_transforms'] = \
                transforms.read_transforms_from_config(
                    cp, 'waveform_transforms')
        return args