Python configparser.ExtendedInterpolation() Examples

The following are 30 code examples of configparser.ExtendedInterpolation(). 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: configparser_test.py    From pycbc with GNU General Public License v3.0 6 votes vote down vote up
def read_ini_file(cpFile):
    """Read a .ini file and return it as a ConfigParser class.
    This function does none of the parsing/combining of sections. It simply
    reads the file and returns it unedited

    Parameters
    ----------
    cpFile : The path to a .ini file to be read in

    Returns
    -------
    cp: The ConfigParser class containing the read in .ini file
    """

    # Initialise ConfigParser class
    cp = ConfigParser.ConfigParser(\
        interpolation=ConfigParser.ExtendedInterpolation())
    # Read the file
    fp = open(cpFile,'r')
    cp.read_file(fp)
    fp.close()
    return cp 
Example #2
Source File: ini.py    From slackbridge with GNU General Public License v3.0 6 votes vote down vote up
def configs_from_inifile(inifile):
    try:
        from configparser import ConfigParser, ExtendedInterpolation
    except ImportError:
        import errno
        raise IOError(
            errno.ENOENT,
            'Missing ConfigParser and ExtendedInterpolation: '
            'please use python3+')
    else:
        parser = ConfigParser(
            allow_no_value=False,     # don't allow "key" without "="
            delimiters=('=',),        # inifile "=" between key and value
            comment_prefixes=(';',),  # only ';' for comments (fixes #channel)
            inline_comment_prefixes=(';',),     # comments after lines
            interpolation=ExtendedInterpolation(),
            empty_lines_in_values=False)  # empty line means new key
        parser.read_file(inifile)
        return BridgeConfigsFromIni(parser).get() 
Example #3
Source File: friar_tuck_run.py    From friartuck with MIT License 6 votes vote down vote up
def get_config(config_filename):
    friar_config = configparser.ConfigParser(
        interpolation=configparser.ExtendedInterpolation(),
        allow_no_value=True,
        delimiters='=',
        inline_comment_prefixes='#'
    )

    local_filename = config_filename.replace('.cfg', '_local.cfg')
    if path.isfile(local_filename):
        config_filename = local_filename

    with open(config_filename, 'r') as file:
        friar_config.read_file(file)

    return friar_config 
Example #4
Source File: settings.py    From pyrdp with GNU General Public License v3.0 6 votes vote down vote up
def load(path: str, fallback: ConfigParser = None) -> ConfigParser:
    """
    Retrieve the PyRDP settings from a file

    :param path: The path of the file to load.
    :param fallback: The fallback configuration path.

    :returns: A ConfigParser instance with the loaded settings.
    :throws Exception: When the fallback configuration is missing and no configuration is found.
    """
    config = ConfigParser(interpolation=ExtendedInterpolation())
    config.optionxform = str
    try:
        if len(config.read(path)) > 0:
            return config
    except Exception:
        # Fallback to default settings.
        pass

    if not fallback:
        raise Exception('Invalid configuration with no fallback specified')
    return fallback 
Example #5
Source File: __init__.py    From autosuspend with GNU General Public License v2.0 5 votes vote down vote up
def parse_config(config_file: Iterable[str]) -> configparser.ConfigParser:
    """Parse the configuration file.

    Args:
        config_file:
            The file to parse
    """
    _logger.debug("Reading config file %s", config_file)
    config = configparser.ConfigParser(
        interpolation=configparser.ExtendedInterpolation()
    )
    config.read_file(config_file)
    _logger.debug("Parsed config file: %s", config)
    return config 
Example #6
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def registration_timeout():
            config = configparser.ConfigParser()
            config._interpolation = configparser.ExtendedInterpolation()
            config.read(System.Ahenk.config_path())
            return config.get('SESSION', 'registration_timeout') 
Example #7
Source File: views.py    From bottle-yang-extractor-validator with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def copy_dependencies(f):
    config_path = '/etc/yangcatalog/yangcatalog.conf'
    config = ConfigParser.ConfigParser()
    config._interpolation = ConfigParser.ExtendedInterpolation()
    config.read(config_path)
    yang_models = config.get('Directory-Section', 'save-file-dir')
    tmp = config.get('Directory-Section', 'temp')
    out = f.getvalue()
    letters = string.ascii_letters
    suffix = ''.join(random.choice(letters) for i in range(8))
    dep_dir = '{}/yangvalidator-dependencies-{}'.format(tmp, suffix)
    os.mkdir(dep_dir)
    dependencies = out.split(':')[1].strip().split(' ')
    for dep in dependencies:
        for file in glob.glob(r'{}/{}*.yang'.format(yang_models, dep)):
            shutil.copy(file, dep_dir)
    return dep_dir 
Example #8
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def plugins_path():
            config = configparser.ConfigParser()
            config._interpolation = configparser.ExtendedInterpolation()
            config.read(System.Ahenk.config_path())
            return config.get('PLUGIN', 'pluginfolderpath') 
Example #9
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def module_name():
            config = configparser.ConfigParser()
            config._interpolation = configparser.ExtendedInterpolation()
            config.read(System.Ahenk.config_path())
            return config.get('PLUGIN', 'mainModuleName') 
Example #10
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def agreement():
            config = configparser.ConfigParser()
            config._interpolation = configparser.ExtendedInterpolation()
            config.read(System.Ahenk.config_path())
            return config.get('MACHINE', 'agreement') 
Example #11
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def machine_type():
            config = configparser.ConfigParser()
            config._interpolation = configparser.ExtendedInterpolation()
            config.read(System.Ahenk.config_path())
            return config.get('MACHINE', 'type') 
Example #12
Source File: utils.py    From Semantic-Texual-Similarity-Toolkits with MIT License 5 votes vote down vote up
def get_config(config_file):
    config = configparser.ConfigParser(allow_no_value=True,
                interpolation=configparser.ExtendedInterpolation())
    config.read(config_file)
    return config 
Example #13
Source File: team.py    From rally with Apache License 2.0 5 votes vote down vote up
def _config_loader(self, file_name):
        config = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
        # Do not modify the case of option keys but read them as is
        config.optionxform = lambda option: option
        config.read(file_name)
        return config 
Example #14
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_policy_timeout():
            config = configparser.ConfigParser()
            config._interpolation = configparser.ExtendedInterpolation()
            config.read(System.Ahenk.config_path())
            return config.get('SESSION', 'get_policy_timeout') 
Example #15
Source File: config.py    From snet-cli with MIT License 5 votes vote down vote up
def __init__(self, _snet_folder = default_snet_folder):
        super(Config, self).__init__(interpolation=ExtendedInterpolation(), delimiters=("=",))
        self._config_file = _snet_folder.joinpath("config")
        if (self._config_file.exists()):
            with open(self._config_file) as f:
                self.read_file(f)
        else:
            self.create_default_config() 
Example #16
Source File: test_configparser.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_get_extended_interpolation(self):
        parser = configparser.ConfigParser(
          interpolation=configparser.ExtendedInterpolation())
        parser.read_string("""
        [Paths]
        home_dir: /Users
        my_dir: ${home_dir1}/lumberjack
        my_pictures: ${my_dir}/Pictures
        """)
        cm = self.assertRaises(configparser.InterpolationMissingOptionError)
        with cm:
            parser.get('Paths', 'my_dir')
        self.assertIs(cm.exception.__suppress_context__, True) 
Example #17
Source File: kvstore.py    From cookiecutter-easydata with MIT License 5 votes vote down vote up
def __init__(self, *args,
                 config_file=None, config_section="KVStore", overwrite=False, persistent=True,
                 **kwargs):
        """Create a new disk-backed key-value store

        Arguments
        ---------
        config_file: Path
            path to ini (ConfigParser-formatted) file that will be used to persist the KVStore
        config_section: String
            Section name to be used in the `config_file`
        overwrite: Boolean
            If True, any config file on disk will be overwritten.
            Otherwise, existing values from this file will be used as defaults,
            (unless overridden by explicit key/value pairs in the constructor)
        *args, **kwargs:
            All other arguments will be used as per the standard `dict` constructor

        """
        self._persistent = persistent
        if config_file is None:
            self._config_file = pathlib.Path("config.ini")
        else:
            self._config_file = pathlib.Path(config_file)
        self._config_section = config_section
        self._config = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())

        self.data = dict()

        if self._config_file.exists() and not overwrite:
            self._config.read(self._config_file)
            if not self._config.has_section(config_section):
                # File exists but we are adding to a new section of it
                self._config.add_section(config_section)
        else:
            self._config.add_section(config_section)
            self._config.read_dict(self.data)

        self.update({k:v for k,v in self._config.items(self._config_section, raw=True)}) # `update` comes for free from the abc
        self.update(dict(*args, **kwargs))
        self._write() 
Example #18
Source File: helper.py    From neuron_poker with MIT License 5 votes vote down vote up
def __init__(self, config_override_filename=None):
        """Load the configuration (usually config.ini)."""
        if config_override_filename and not os.path.isfile(config_override_filename):
            raise ValueError("Unable to find config file {}".format(config_override_filename))

        main_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.ini')

        self.config = ConfigParser(interpolation=ExtendedInterpolation())
        self.config.optionxform = str  # enforce case sensitivity on key

        if config_override_filename:  # custom config
            self.config.read([main_file, config_override_filename])
        else:  # no custom file
            self.config.read(main_file) 
Example #19
Source File: Settings.py    From Open365 with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self,
                 override_settings_path='settings.cfg'):
        self.settingsFilePath = override_settings_path
        self.parser = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
        self.settings = None
        self.getSettings() 
Example #20
Source File: io_06.py    From Modern-Python-Standard-Library-Cookbook with MIT License 5 votes vote down vote up
def read_config(config_text, schema=None):
    """Read options from ``config_text`` applying given ``schema``"""
    schema = schema or {}

    cfg = configparser.ConfigParser(
        interpolation=configparser.ExtendedInterpolation()
    )
    try:
        cfg.read_string(config_text)
    except configparser.MissingSectionHeaderError:
        config_text = '[main]\n' + config_text
        cfg.read_string(config_text)

    config = {}
    for section in schema:
        options = config.setdefault(section, {})
        for option, option_schema in schema[section].items():
            options[option] = option_schema.get('default')
    for section in cfg.sections():
        options = config.setdefault(section, {})
        section_schema = schema.get(section, {})
        for option in cfg.options(section):
            option_schema = section_schema.get(option, {})
            getter = 'get' + option_schema.get('type', '')
            options[option] = getattr(cfg, getter)(section, option)
    return config 
Example #21
Source File: command_manager.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def clean(self):
        print('Ahenk cleaning..')
        try:
            config = configparser.ConfigParser()
            config._interpolation = configparser.ExtendedInterpolation()
            config.read(System.Ahenk.config_path())
            db_path = config.get('BASE', 'dbPath')

            if Util.is_exist(System.Ahenk.fifo_file()):
                Util.delete_file(System.Ahenk.fifo_file())

            if Util.is_exist(db_path):
                Util.delete_file(db_path)

            if Util.is_exist(System.Ahenk.pid_path()):
                Util.delete_file(System.Ahenk.pid_path())

            config.set('CONNECTION', 'uid', '')
            config.set('CONNECTION', 'password', '')

            with open(System.Ahenk.config_path(), 'w') as file:
                config.write(file)
            file.close()
            print('Ahenk cleaned.')
        except Exception as e:
            print('Error while running clean command. Error Message {0}'.format(str(e))) 
Example #22
Source File: config.py    From hgvs with Apache License 2.0 5 votes vote down vote up
def __init__(self, extended_interpolation=True):
        if extended_interpolation:
            cp = ConfigParser(interpolation=ExtendedInterpolation())
        else:
            cp = ConfigParser()
        cp.optionxform = _name_xform
        self._cp = cp 
Example #23
Source File: config.py    From neural-el with Apache License 2.0 5 votes vote down vote up
def __init__(self, paths_config, verbose=False):
        config = configparser.ConfigParser()
        config._interpolation = configparser.ExtendedInterpolation()
        config.read(paths_config)
        print(paths_config)

        c = config['DEFAULT']

        d = {}
        for k in c:
            d[k] = c[k]

        self.resources_dir = d['resources_dir']

        self.vocab_dir = d['vocab_dir']

        # Word2Vec Vocab to Idxs
        self.word_vocab_pkl = d['word_vocab_pkl']
        # Wid2Idx for Known Entities ~ 620K (readers.train.vocab.py)
        self.kwnwid_vocab_pkl = d['kwnwid_vocab_pkl']
        # FIGER Type label 2 idx (readers.train.vocab.py)
        self.label_vocab_pkl = d['label_vocab_pkl']
        # EntityWid: [FIGER Type Labels]
        # CoherenceStr2Idx at various thresholds (readers.train.vocab.py)
        self.cohstringG9_vocab_pkl = d['cohstringg9_vocab_pkl']

        # wid2Wikititle for whole KB ~ 3.18M (readers.train.vocab.py)
        self.widWiktitle_pkl = d['widwiktitle_pkl']

        self.crosswikis_pruned_pkl = d['crosswikis_pruned_pkl']

        self.glove_pkl = d['glove_pkl']
        self.glove_word_vocab_pkl = d['glove_word_vocab_pkl']

        self.test_file = d['test_file']

        if verbose:
            pp.pprint(d)

    #endinit 
Example #24
Source File: config.py    From Parser-v3 with Apache License 2.0 5 votes vote down vote up
def __init__(self, defaults_file=os.path.join('config', 'defaults.cfg'), config_file='', **kwargs):
    """"""
    
    #super(Config, self).__init__(defaults=kwargs.pop('DEFAULT', {}))
    super(Config, self).__init__(interpolation=ExtendedInterpolation())
    self.read([defaults_file, config_file])
    for section, options in six.iteritems(kwargs):
      if section != 'DEFAULT' and not self.has_section(section):
        self.add_section(section)
      for option, value in six.iteritems(options):
        self.set(section, option, str(value))
    return
  
  #============================================================= 
Example #25
Source File: test_configparser.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_get_extended_interpolation(self):
        parser = configparser.ConfigParser(
          interpolation=configparser.ExtendedInterpolation())
        parser.read_string("""
        [Paths]
        home_dir: /Users
        my_dir: ${home_dir1}/lumberjack
        my_pictures: ${my_dir}/Pictures
        """)
        cm = self.assertRaises(configparser.InterpolationMissingOptionError)
        with cm:
            parser.get('Paths', 'my_dir')
        self.assertIs(cm.exception.__suppress_context__, True) 
Example #26
Source File: prefs.py    From ads2bibdesk with GNU General Public License v3.0 5 votes vote down vote up
def _get_prefs(self):
        """
        """

        prefs = ConfigParser(interpolation=ExtendedInterpolation())
        prefs.read_string("""
        
            [default]
            ads_token = dev_key
            
            [proxy]
            ssh_user = None
            ssh_server = None
            ssh_port = 22
            
            [options]
            download_pdf = True
            alert_sound = True
            debug = False            
                          
            """)
        prefs_dir = os.path.dirname(self.prefs_path)

        if not os.path.exists(prefs_dir):
            os.makedirs(prefs_dir)
        if not os.path.exists(self.prefs_path):
            with open(self.prefs_path, 'w') as prefs_file:
                prefs.write(prefs_file)
        else:
            prefs.read(self.prefs_path)

        return prefs 
Example #27
Source File: registration.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def clean(self):
        print('Ahenk cleaning..')
        import configparser
        try:
            config = configparser.ConfigParser()
            config._interpolation = configparser.ExtendedInterpolation()
            config.read(System.Ahenk.config_path())
            db_path = config.get('BASE', 'dbPath')

            if Util.is_exist(System.Ahenk.fifo_file()):
                Util.delete_file(System.Ahenk.fifo_file())

            if Util.is_exist(db_path):
                Util.delete_file(db_path)

            if Util.is_exist(System.Ahenk.pid_path()):
                Util.delete_file(System.Ahenk.pid_path())

            config.set('CONNECTION', 'uid', '')
            config.set('CONNECTION', 'password', '')
            config.set('CONNECTION', 'host', '')
            config.set('MACHINE', 'user_disabled', 'false')

            with open(System.Ahenk.config_path(), 'w') as file:
                config.write(file)
            file.close()
            print('Ahenk cleaned.')
        except Exception as e:
            self.logger.error("Error while running clean command. Error Message  " + str(e))
            print('Error while running clean command. Error Message {0}'.format(str(e))) 
Example #28
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def agreement_timeout():
            config = configparser.ConfigParser()
            config._interpolation = configparser.ExtendedInterpolation()
            config.read(System.Ahenk.config_path())
            return config.get('SESSION', 'agreement_timeout') 
Example #29
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def db_path():
            config = configparser.ConfigParser()
            config._interpolation = configparser.ExtendedInterpolation()
            config.read(System.Ahenk.config_path())
            return config.get('BASE', 'dbPath') 
Example #30
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def agreement_timeout():
            config = configparser.ConfigParser()
            config._interpolation = configparser.ExtendedInterpolation()
            config.read(System.Ahenk.config_path())
            return config.get('SESSION', 'agreement_timeout')