Parse an ini file

    :param path: The path to a file to parse
    :type file: str
    :returns: Configuration contained in path
    :rtype: Dict
337233
def _config_ini(path):
    
    conf = configparser.ConfigParser()
    conf.read(path)
    return dict(conf)
960805
def parse(file_path):
    ''''''

    _, ext = path.splitext(file_path)

    if ext in ('.yaml', '.yml'):
        func = yaml.load

    elif ext == '.json':
        func = json.load

    else:
        raise ValueError("Unrecognized config file type %s" % ext)

    with open(file_path, 'r') as f:
        return func(f)
466305
def load_from_path(path: str) -> Config:
    
    data = _ensure_load(path)
    if not data:
        data = {}
    values, should_write = _ensure_values(data)
    values.update({'path': path})
    config = Config(**values)
    if config.signature_required:
        if not os.path.exists(config.update_cert_path):
            LOG.warning(
                f"No signing cert is present in {config.update_cert_path}, "
                "code signature checking disabled")
            config = config._replace(signature_required=False)
            config = config._replace(update_cert_path=DEFAULT_CERT_PATH)
    if should_write:
        save_to_path(path, config)
    return config
376109
def read_key_value_pairs_from_file(*path):
    
    with open(os.path.join(*path)) as f:
        for line in f:
            yield line.split(' ', 1)
773746
def _load_config(self, path):
        
        try:
            with open(path) as f:
                values = yaml.safe_load(f)
                if isinstance(values, dict):
                    return values
                else:
                    raise yaml.YAMLError('Unable to parse/load {}'.format(path))
        except(IOError, yaml.YAMLError) as e:
            if self.ignore_errors:
                return None
            else:
                raise e
1065766
def read_config_info(ini_file):
    
    try:
        config = RawConfigParser()
        config.optionxform = lambda option: option
        config.read(ini_file)
        the_stuff = {}
        for section in config.sections():
            the_stuff[section] = {}
            for option in config.options(section):
                the_stuff[section][option] = config.get(section, option)

        return the_stuff
    except Exception as wtf:
        logging.error('Exception caught in read_config_info(): {}'.format(wtf))
        traceback.print_exc(file=sys.stdout)
        return sys.exit(1)
643035
def _load_config(self, path):
        '''
        
        '''
        config = {}
        log.debug('Reading configuration from %s', path)
        if not os.path.isdir(path):
            msg = (
                'Unable to read from {path}: '
                'the directory does not exist!'
            ).format(path=path)
            log.error(msg)
            raise IOError(msg)
        # The directory tree should look like the following:
        # .
        # ├── __init__.py
        # ├── eos
        # │   └── init.yml
        # ├── iosxr
        # │   └── __init__.py
        # ├── junos
        # │   └── init.yml
        # │   └── bgp_read_message.py
        # │   └── BGP_PREFIX_THRESH_EXCEEDED.py
        # └── nxos
        #     └── init.yml
        os_subdirs = [sdpath[0] for sdpath in os.walk(path)][1:]
        if not os_subdirs:
            log.error('%s does not contain any OS subdirectories', path)
        for os_dir in os_subdirs:
            os_name = os.path.split(os_dir)[1]  # the network OS name
            if os_name.startswith('__'):
                log.debug('Ignoring %s', os_name)
                continue
            if not self._whitelist_blacklist(os_name):
                log.debug('Not building config for %s (whitelist-blacklist logic)', os_name)
                # Ignore devices that are not in the whitelist (if defined),
                #   or those operating systems that are on the blacklist.
                # This way we can prevent starting unwanted sub-processes.
                continue
            log.debug('Building config for %s:', os_name)
            log.debug('='*40)
            if os_name not in config:
                config[os_name] = {}
            files = os.listdir(os_dir)
            # Read all files under the OS dir
            for file_ in files:
                log.debug('Inspecting %s', file_)
                file_name, file_extension = os.path.splitext(file_)
                file_extension = file_extension.replace('.', '')
                filepath = os.path.join(os_dir, file_)
                comment = ''
                if file_extension in ('yml', 'yaml'):
                    try:
                        log.debug('Loading %s as YAML', file_)
                        with open(filepath, 'r') as fstream:
                            cfg = yaml.load(fstream)
                            # Reposition at the top and read the comments.
                            if file_name not in CONFIG.OS_INIT_FILENAMES:
                                # If the file name is not a profile init.
                                fstream.seek(0)
                                comment = self._extract_yaml_docstring(fstream)
                                if 'messages' in cfg:
                                    for message in cfg['messages']:
                                        message['__doc__'] = comment
                            napalm_logs.utils.dictupdate(config[os_name], cfg)
                    except yaml.YAMLError as yamlexc:
                        log.error('Invalid YAML file: %s', filepath, exc_info=True)
                        if file_name in CONFIG.OS_INIT_FILENAMES:
                            # Raise exception and break only when the init file is borked
                            #   otherwise, it will try loading best efforts.
                            raise IOError(yamlexc)
                elif file_extension == 'py':
                    log.debug('Lazy loading Python module %s', file_)
                    mod_fp, mod_file, mod_data = imp.find_module(file_name, [os_dir])
                    mod = imp.load_module(file_name, mod_fp, mod_file, mod_data)
                    if file_name in CONFIG.OS_INIT_FILENAMES:
                        # Init file defined as Python module
                        log.debug('%s seems to be a Python profiler', filepath)
                        # Init files require to define the `extract` function.
                        # Sample init file:
                        # def extract(message):
                        #     return {'tag': 'A_TAG', 'host': 'hostname'}
                        if hasattr(mod, CONFIG.INIT_RUN_FUN) and\
                           hasattr(getattr(mod, CONFIG.INIT_RUN_FUN), '__call__'):
                            # if extract is defined and is callable
                            if 'prefixes' not in config[os_name]:
                                config[os_name]['prefixes'] = []
                            config[os_name]['prefixes'].append({
                                'values': {'tag': ''},
                                'line': '',
                                '__python_fun__': getattr(mod, CONFIG.INIT_RUN_FUN),
                                '__python_mod__': filepath  # Will be used for debugging
                            })
                            log.info('Adding the prefix function defined under %s to %s',
                                     filepath, os_name)
                        elif file_name != '__init__':
                            # If __init__.py does not have the extractor function, no problem.
                            log.warning('%s does not have the "%s" function defined. Ignoring.',
                                        filepath, CONFIG.INIT_RUN_FUN)
                    else:
                        # Other python files require the `emit` function.
                        if hasattr(mod, '__tag__'):
                            mod_tag = getattr(mod, '__tag__')
                        else:
                            log.info('%s does not have __tag__, defaulting the tag to %s', filepath, file_name)
                            mod_tag = file_name
                        if hasattr(mod, '__error__'):
                            mod_err = getattr(mod, '__error__')
                        else:
                            log.info('%s does not have __error__, defaulting the error to %s', filepath, file_name)
                            mod_err = file_name
                        if hasattr(mod, '__match_on__'):
                            err_match = getattr(mod, '__match_on__')
                        else:
                            err_match = 'tag'
                        model = CONFIG.OPEN_CONFIG_NO_MODEL
                        if hasattr(mod, '__yang_model__'):
                            model = getattr(mod, '__yang_model__')
                        log.debug('Mathing on %s', err_match)
                        if hasattr(mod, CONFIG.CONFIG_RUN_FUN) and\
                           hasattr(getattr(mod, CONFIG.CONFIG_RUN_FUN), '__call__'):
                            log.debug('Adding %s with tag:%s, error:%s, matching on:%s',
                                      file_, mod_tag, mod_err, err_match)
                            # the structure below must correspond to the VALID_CONFIG structure enforcement
                            if 'messages' not in config[os_name]:
                                config[os_name]['messages'] = []
                            config[os_name]['messages'].append({
                                'tag': mod_tag,
                                'error': mod_err,
                                'match_on': err_match,
                                '__doc__': mod.__doc__,
                                '__python_fun__': getattr(mod, CONFIG.CONFIG_RUN_FUN),
                                '__python_mod__': filepath,  # Will be used for debugging
                                'line': '',
                                'model': model,
                                'values': {},
                                'mapping': {'variables': {}, 'static': {}}
                            })
                        else:
                            log.warning('%s does not have the "%s" function defined. Ignoring.',
                                        filepath, CONFIG.CONFIG_RUN_FUN)
                else:
                    log.info('Ignoring %s (extension not allowed)', filepath)
            log.debug('-'*40)
        if not config:
            msg = 'Could not find proper configuration files under {path}'.format(path=path)
            log.error(msg)
            raise IOError(msg)
        log.debug('Complete config:')
        log.debug(config)
        log.debug('ConfigParserg size in bytes: %d', sys.getsizeof(config))
        return config
1931
def read(in_path):
    
    assert os.path.exists(in_path), "The following GRP file can't be found. in_path: {}".format(in_path)

    with open(in_path, "r") as f:
        lines = f.readlines()
        # need the second conditional to ignore comment lines
        grp = [line.strip() for line in lines if line and not re.match("^#", line)]

    return grp
14994
def load_configuration(conf_path):
    
    with open(conf_path) as f:
        conf_dict = yaml.load(f)
    validate_config(conf_dict)
    return conf_dict
1031854
def read_file(self, path, **kwargs):
        
        try:
            parsed_data = Parser().parse_file(path)
            return parsed_data
        except (IOError, TypeError, ImportError):
            LOGGER.warning("Error reading file: {0}".format(path))
        return None
543073
def _read_conf_file(path):
    '''
    
    '''
    log.debug('Reading configuration from %s', path)
    with salt.utils.files.fopen(path, 'r') as conf_file:
        try:
            conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
        except salt.utils.yaml.YAMLError as err:
            message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
            log.error(message)
            raise salt.exceptions.SaltConfigurationError(message)

        # only interpret documents as a valid conf, not things like strings,
        # which might have been caused by invalid yaml syntax
        if not isinstance(conf_opts, dict):
            message = 'Error parsing configuration file: {0} - conf ' \
                      'should be a document, not {1}.'.format(path, type(conf_opts))
            log.error(message)
            raise salt.exceptions.SaltConfigurationError(message)

        # allow using numeric ids: convert int to string
        if 'id' in conf_opts:
            if not isinstance(conf_opts['id'], six.string_types):
                conf_opts['id'] = six.text_type(conf_opts['id'])
            else:
                conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
        return conf_opts
502764
def read_config(config_path_or_dict=None):
    
    config = None

    if isinstance(config_path_or_dict, dict):
        config = Config(config_path_or_dict)

    if isinstance(config_path_or_dict, string_types):
        if os.path.isabs(config_path_or_dict):
            config_path = config_path_or_dict
        else:
            config_path = os.path.join(
                os.getcwd(),
                os.path.normpath(config_path_or_dict)
            )
    else:
        config_path = os.path.join(
            os.getcwd(),
            DEFAULT_CONFIG_PATH
        )

    if os.path.exists(config_path):
        with open(config_path, 'r') as f:
            data = json.load(f)
            config = Config(data)

    if config is None:
        raise ConfigNotFound()
    else:
        config.validate()

        return config
185469
def from_file(cls, config_path=None, *args, **kwargs):
        

        config_reader = kaptan.Kaptan()

        config = {}

        if config_path:
            if not os.path.exists(config_path):
                raise exc.CihaiException(
                    '{0} does not exist.'.format(os.path.abspath(config_path))
                )
            if not any(
                config_path.endswith(ext) for ext in ('json', 'yml', 'yaml', 'ini')
            ):
                raise exc.CihaiException(
                    '{0} does not have a yaml,yml,json,ini extend.'.format(
                        os.path.abspath(config_path)
                    )
                )
            else:
                custom_config = config_reader.import_config(config_path).get()
                config = merge_dict(config, custom_config)

        return cls(config)
503362
def integration_and_config(self, path):
        
        if path.startswith(tuple(INTEGRATION_MAP.keys())):
            key = INTEGRATION_MAP[path.split(":")[0] + ":"]
            integration = self._integrations.get(key)
            config = {}
            for sample in self._samples:
                config = tz.get_in(["config", key], sample)
                if config:
                    break
            return integration, config

        return None, None
1051763
def parsed_file(config_file):
    """"""
    parser = ConfigParser(allow_no_value=True)
    parser.readfp(config_file)
    return parser
966057
def parseConfigFile(configFile=None):
    

    # 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
1328396
def _load(self, file_path: Text) -> None:
        

        # noinspection PyUnresolvedReferences
        module_ = types.ModuleType('settings')
        module_.__file__ = file_path

        try:
            with open(file_path, encoding='utf-8') as f:
                exec(compile(f.read(), file_path, 'exec'), module_.__dict__)
        except IOError as e:
            e.strerror = 'Unable to load configuration file ({})'\
                .format(e.strerror)
            raise

        for key in dir(module_):
            if CONFIG_ATTR.match(key):
                self[key] = getattr(module_, key)