Beispiel #1
0
def set_namespace_options(namespace, options, remove=None):
    """
    Set options in the local namespace configuration file.
    Can have nasty effects, be careful, only use in test code.

    :param namespace: the namespace to work with
    :param options: a dictionary with options to set
    :param remove: an iterable of options to remove
    :returns: a dictionary with all options of the namespace
    """
    parser = SafeConfigParser({})

    potential_confs = list()
    actual_confs = list()
    for p, _ in _config_paths():
        potential_confs.append(p)
        fdone = parser.read((p,))
        actual_confs.extend(fdone)
    if not actual_confs:
        raise ValueError(
            "Could not read configuration from any of %s" % potential_confs)

    if not parser.has_section(namespace):
        print('Namespace %s was not found in %s' % (namespace, actual_confs))
        parser.add_section(namespace)
    for key, val in options.items():
        parser.set(namespace, key, str(val))
    if remove:
        for key in remove:
            parser.remove_option(namespace, key)

    with open(actual_confs[-1], 'w') as outfile:
        parser.write(outfile)
    return dict(parser.items(namespace))
def init_ini_file(file=args.ini_file):
    cp=SafeConfigParser()
    fp=open(file)
    cp.optionxform = str
    cp.readfp(fp)
    fp.close()

    cp.set('condor','lalsuite-install',lalinf_prefix)
    cp.set('analysis','engine',args.engine)
    cp.remove_option('analysis','nparallel')

    return cp
Beispiel #3
0
def init_ini_file(file=args.ini_file):
    cp = SafeConfigParser()
    fp = open(file)
    cp.optionxform = str
    cp.readfp(fp)
    fp.close()

    cp.set('condor', 'lalsuite-install', lalinf_prefix)
    cp.set('analysis', 'engine', args.engine)
    cp.remove_option('analysis', 'nparallel')

    return cp
Beispiel #4
0
class Config(MutableMapping):
    """Read and write to config file.

    A config object is essentially a string key-value store that can be treated like a dictionary::

        c = Config()
        c['foo'] = 'bar'
        print c['foo']

    The file location may be specified::

        c = Config('~/matt/anotherconfig.cfg')
        c['where'] = 'in a different file'

    If no location is specified, the environment variable CHEMDATAEXTRACTOR_CONFIG is checked and used if available.
    Otherwise, a standard config location is used, which varies depending on the operating system. You can check the
    location using the ``path`` property. For more information see https://github.com/ActiveState/appdirs

    It is possible to edit the file by hand with a text editor.

    Warning: multiple instances of Config() pointing to the same file will not see each others' changes, and will
    overwrite the entire file when any key is changed.

    """

    #: These values will be present in a config object unless they are explicitly defined otherwise in the config file
    default_values = {}

    def __init__(self, path=None):
        """

        :param string path: (Optional) Path to config file location.
        """
        self._path = path

        # Use CHEMDATAEXTRACTOR_CONFIG environment variable if set
        if not self._path:
            self._path = os.environ.get('CHEMDATAEXTRACTOR_CONFIG')
        # Use OS-dependent config directory given by appdirs
        if not self._path:
            self._path = os.path.join(
                appdirs.user_config_dir('ChemDataExtractor'), 'config.cfg')
        self._parser = SafeConfigParser()
        if os.path.isfile(self.path):
            with open(self.path) as f:
                self._parser.readfp(f)
        if not self._parser.has_section('cde'):
            self._parser.add_section('cde')
        for k, v in six.iteritems(self.default_values):
            if not self._parser.has_option('cde', k.encode('utf-8')):
                self._parser.set('cde', k.encode('utf-8'), v.encode('utf-8'))

    @property
    def path(self):
        """The path to the config file."""
        return self._path

    def _flush(self):
        """Save the contents of data to the file on disk. You should not need to call this manually."""
        d = os.path.dirname(self.path)
        if not os.path.isdir(d):
            os.makedirs(d)
        with open(self.path, 'w') as f:
            self._parser.write(f)

    def __contains__(self, k):
        return self._parser.has_option('cde', k.encode('utf-8'))

    def __getitem__(self, k):
        try:
            return self._parser.get('cde', k.encode('utf-8'))
        except NoOptionError:
            raise KeyError(k)

    def __setitem__(self, k, v):
        self._parser.set('cde', k.encode('utf-8'), v.encode('utf-8'))
        self._flush()

    def __delitem__(self, k):
        try:
            self._parser.remove_option('cde', k.encode('utf-8'))
            self._flush()
        except NoOptionError:
            raise KeyError(k)

    def __iter__(self):
        return (k for k, v in self._parser.items('cde'))

    def __len__(self):
        return len(self._parser.items('cde'))

    def __repr__(self):
        return '<Config: %s>' % self.path

    def clear(self):
        """Clear all values from config."""
        self._parser.remove_section('cde')
        self._parser.add_section('cde')
        self._flush()