当前位置: 首页>>代码示例>>Python>>正文


Python ConfigParser.options方法代码示例

本文整理汇总了Python中six.moves.configparser.ConfigParser.options方法的典型用法代码示例。如果您正苦于以下问题:Python ConfigParser.options方法的具体用法?Python ConfigParser.options怎么用?Python ConfigParser.options使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在six.moves.configparser.ConfigParser的用法示例。


在下文中一共展示了ConfigParser.options方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: loadKeysConfig

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import options [as 别名]
def loadKeysConfig(path=None):
	"""Load keys config file.

	If path is ``None``, a file named :any:`DEFAULT_KEYS_FILE` will be looked for in the config
	directory.

	:param path: path of the keyboard configuration file
	"""

	if path is None:
		path = getConfigFilePath(DEFAULT_KEYS_FILE)

	cfg = ConfigParser()
	cfg.optionxform = str
	cfg.read([path])

	for category in cfg.sections():
		for actionName in cfg.options(category):
			keystr = cfg.get(category, actionName)

			context = Qt.WidgetShortcut
			if keystr.startswith('widget:'):
				keystr = keystr.split(':', 1)[1]
			elif keystr.startswith('window:'):
				keystr = keystr.split(':', 1)[1]
				context = Qt.WindowShortcut
			elif keystr.startswith('children:'):
				keystr = keystr.split(':', 1)[1]
				context = Qt.WidgetWithChildrenShortcut
			elif keystr.startswith('application:'):
				keystr = keystr.split(':', 1)[1]
				context = Qt.ApplicationShortcut
			qks = QKeySequence(keystr)

			registerActionShortcut(category, actionName, qks, context)
开发者ID:hydrargyrum,项目名称:eye,代码行数:37,代码来源:keys.py

示例2: get_config

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import options [as 别名]
def get_config(p):
    """Read a config file.

    :return: dict of ('section.option', value) pairs.
    """
    cfg = {}
    parser = ConfigParser()
    if hasattr(parser, 'read_file'):
        parser.read_file(Path(p).open(encoding='utf8'))
    else:  # pragma: no cover
        assert PY2
        # The `read_file` method is not available on ConfigParser in py2.7!
        parser.readfp(Path(p).open(encoding='utf8'))

    for section in parser.sections():
        getters = {
            'int': partial(parser.getint, section),
            'boolean': partial(parser.getboolean, section),
            'float': partial(parser.getfloat, section),
            'list': lambda option: parser.get(section, option).split(),
        }
        default = partial(parser.get, section)
        for option in parser.options(section):
            type_ = option.rpartition('_')[2] if '_' in option else None
            value = getters.get(type_, default)(option)
            cfg['{0}.{1}'.format(section, option)] = value

    return cfg
开发者ID:clld,项目名称:clld,代码行数:30,代码来源:config.py

示例3: restore_rois

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import options [as 别名]
    def restore_rois(self, roifile):
        """restore ROI setting from ROI.dat file"""
        cp =  ConfigParser()
        cp.read(roifile)
        rois = []
        self.mcas[0].clear_rois()
        prefix = self.mcas[0]._prefix
        if prefix.endswith('.'):
            prefix = prefix[:-1]
        iroi = 0
        for a in cp.options('rois'):
            if a.lower().startswith('roi'):
                name, dat = cp.get('rois', a).split('|')
                lims = [int(i) for i in dat.split()]
                lo, hi = lims[0], lims[1]
                # print('ROI ', name, lo, hi)
                roi = ROI(prefix=prefix, roi=iroi)
                roi.LO = lo
                roi.HI = hi
                roi.NM = name.strip()
                rois.append(roi)
                iroi += 1

        poll(0.050, 1.0)
        self.mcas[0].set_rois(rois)
        cal0 = self.mcas[0].get_calib()
        for mca in self.mcas[1:]:
            mca.set_rois(rois, calib=cal0)
开发者ID:maurov,项目名称:xraylarch,代码行数:30,代码来源:xspress3.py

示例4: test_empty_dict

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import options [as 别名]
    def test_empty_dict(self):
        name = self.make_empty_temp_file()
        to_config_file(name, "section.name", {})

        self.assertTrue(os.path.isfile(name))

        config = ConfigParser()
        config.read(name)
        self.assertTrue(config.has_section("section.name"))
        self.assertSetEqual(_VALID_KEYS, set(config.options("section.name")))
开发者ID:csdms,项目名称:pymt,代码行数:12,代码来源:test_component_info.py

示例5: test_partial_dict

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import options [as 别名]
    def test_partial_dict(self):
        name = self.make_empty_temp_file()
        to_config_file(name, "section.name", {"port_queue_dt": 1.})

        self.assertTrue(os.path.isfile(name))

        config = ConfigParser()
        config.read(name)
        self.assertTrue(config.has_section("section.name"))
        self.assertSetEqual(_VALID_KEYS, set(config.options("section.name")))
        self.assertEqual(1., config.getfloat("section.name", "port_queue_dt"))
开发者ID:csdms,项目名称:pymt,代码行数:13,代码来源:test_component_info.py

示例6: _read

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import options [as 别名]
 def _read(self):
     parser = ConfigParser()
     parser.read(self.path)
     self._globals = parser.defaults()
     data = {}
     for section in parser.sections():
         section_data = data.setdefault(section, {})
         for option in parser.options(section):
             if option in self._globals:
                 continue
             section_data[option] = parser.get(section, option)
     return data
开发者ID:stevepiercy,项目名称:montague,代码行数:14,代码来源:ini.py

示例7: _load

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import options [as 别名]
    def _load(self):
        self.files = self.options

        config = ConfigParser()

        for filepath in self.files:
            with codecs.open(filepath, 'r', encoding='utf-8') as stream:
                fakefile = StringIO("[top]\n" + stream.read())
                config.readfp(fakefile)

        return [self._l10n2rec(key, config.get('top', key))
                for key in config.options('top')]
开发者ID:mozilla-services,项目名称:l10n2kinto,代码行数:14,代码来源:l10n.py

示例8: test_ignore_extra_params

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import options [as 别名]
    def test_ignore_extra_params(self):
        name = self.make_empty_temp_file()
        to_config_file(
            name, "section.name", {"invalid_parameter": "empty", "port_queue_dt": 1.2}
        )

        self.assertTrue(os.path.isfile(name))

        config = ConfigParser()
        config.read(name)
        self.assertTrue(config.has_section("section.name"))
        self.assertSetEqual(_VALID_KEYS, set(config.options("section.name")))
        self.assertEqual(1.2, config.getfloat("section.name", "port_queue_dt"))
        self.assertFalse(config.has_option("section.name", "invalid_parameter"))
开发者ID:csdms,项目名称:pymt,代码行数:16,代码来源:test_component_info.py

示例9: restore_rois

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import options [as 别名]
    def restore_rois(self, roifile):
        """restore ROI setting from ROI.dat file"""
        cp = ConfigParser()
        cp.read(roifile)
        roidat = []
        for a in cp.options('rois'):
            if a.lower().startswith('roi'):
                name, dat = cp.get('rois', a).split('|')
                lims = [int(i) for i in dat.split()]
                lo, hi = lims[0], lims[1]
                roidat.append((name.strip(), lo, hi))

        for mca in self.mcas:
            mca.set_rois(roidat)
开发者ID:pyepics,项目名称:stepscan,代码行数:16,代码来源:xspress3.py

示例10: read_test_ini

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import options [as 别名]
def read_test_ini(file_dir=FILE_DIR, section="FacebookAuth"):
    ini_file_path = os.path.join(file_dir, "test.ini")
    ret = {}
    if os.path.isfile(ini_file_path):
        cp = ConfigParser()
        cp.read(ini_file_path)
        if section not in cp.sections():
            raise EnvironmentError(
                "Section '{0}' not in test.ini".format(section))
        for arg in cp.options(section):
            ret[arg] = cp.get(section, arg)
    else:
        raise EnvironmentError(
            "File test.ini not existing in path '{0}'".format(FILE_DIR))
    return ret
开发者ID:AliakseiKorneu,项目名称:pynder,代码行数:17,代码来源:utils.py

示例11: load

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import options [as 别名]
    def load(self):
        cfp = ConfigParser()
        # p = os.path.join(paths.spectrometer_dir, 'config.cfg')
        p = get_spectrometer_config_path()
        cfp.read(p)
        gs = []
        for section in cfp.sections():
            g = SpectrometerParametersGroup(name=section)
            ps = []
            for pp in cfp.options(section):
                v = cfp.getfloat(section, pp)
                ps.append(Parameter(name=pp, value=v))

            g.parameters = ps
            gs.append(g)

        self.groups = gs
开发者ID:NMGRL,项目名称:pychron,代码行数:19,代码来源:spectrometer_parameters.py

示例12: _get_names_from_config

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import options [as 别名]
 def _get_names_from_config(self, cp, section):
     config = ConfigParser()
     config.read(cp)
     if config.has_section(section):
         return [config.get(section, option) for option in config.options(section)]
开发者ID:NMGRL,项目名称:pychron,代码行数:7,代码来源:factory.py

示例13: SpecConfig

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import options [as 别名]
class SpecConfig(object):
    #  sections            name      ordered?
    __sects = OrderedDict((('setup',     False),
                           ('motors',    True),
                           ('detectors', True),
                           ('extra_pvs', True),
                           ('counters',  True)))

    def __init__(self, filename=None, text=None):
        for s in self.__sects:
            setattr(self, s, {})

        self._cp = ConfigParser()
        if filename is None:
            if (os.path.exists(DEF_CONFFILE) and
                os.path.isfile(DEF_CONFFILE)):
                filename = DEF_CONFFILE

        self.filename = filename
        if filename is not None:
            self.Read(filename)

    def Read(self, fname):
        "read config"
        if fname is None:
            return
        ret = self._cp.read(fname)
        if len(ret) == 0:
            time.sleep(0.25)
            ret = self._cp.read(fname)
        self.filename = fname
        # process sections
        for sect, ordered in self.__sects.items():
            if not self._cp.has_section(sect):
                continue
            thissect = {}
            if ordered:
                thissect = OrderedDict()
            for opt in self._cp.options(sect):
                val = self._cp.get(sect, opt)
                if '||' in val:
                    words = [i.strip() for i in val.split('||')]
                    label = words.pop(0)
                    if len(words) == 1:
                        words = words[0]
                    else:
                        words = tuple(words)
                    thissect[label] = words
                else:
                    thissect[opt] = val
                setattr(self, sect, thissect)

    def Save(self, fname=None):
        "save config file"
        if fname is not None:
            self.filename = fname
        if fname is None:
            fname = self.filename = DEF_CONFFILE
            path, fn = os.path.split(fname)
            if not os.path.exists(path):
                os.makedirs(path, mode=0o755)

        out = ['###PyScan Spec Configuration: %s'  % (get_timestamp())]
        for sect, ordered in self.__sects.items():
            out.append('#-----------------------#\n[%s]' % sect)
            if sect == 'setup':
                for name, val in self.setup.items():
                    out.append("%s = %s" % (name, val))
            elif sect == 'detectors':
                out.append(DET_LEGEND)
                print( 'sect = det')
                idx = 0
                for key, val in getattr(self, sect).items():
                    idx = idx + 1
                    if isinstance(val, (list, tuple)):
                        val = ' || '.join(val)
                    out.append("%i = %s || %s"  % (idx, key, val))

            else:
                leg = LEGEND
                out.append(LEGEND)
                idx = 0
                for key, val in getattr(self, sect).items():
                    idx = idx + 1
                    if isinstance(val, (list, tuple)):
                        val = ' || '.join(val)
                    out.append("%i = %s || %s"  % (idx, key, val))
        out.append('#-----------------------#')
        f = open(fname, 'w')
        f.write('\n'.join(out))
        f.close()

    def sections(self):
        return self.__sects.keys()
开发者ID:pyepics,项目名称:stepscan,代码行数:96,代码来源:spec_config.py

示例14: StationConfig

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import options [as 别名]
class StationConfig(object):
    #  sections            name      ordered?
    __sects = OrderedDict((('setup',       False),
                           ('server',   False),
                           ('positioners', True),
                           ('detectors',   True),
                           ('counters',    True),
                           ('xafs',        False),
                           ('slewscan',    False),
                           ('slewscan_positioners',  True),
                           ('extrapvs',   True),
                           ))

    def __init__(self, filename=None, text=None):
        for s in self.__sects:
           setattr(self, s, {})

        self._cp = ConfigParser()
        if filename is None:
            filename = DEF_CONFFILE
        self.filename = filename
        # print 'StationConfig ', filename, os.path.abspath(filename)
        # print os.path.exists(filename),   os.path.isfile(filename)
        if (os.path.exists(filename) and
            os.path.isfile(filename)):
            ret = self._cp.read(filename)
            if len(ret) == 0:
                time.sleep(0.1)
                self._cp.read(filename)
        else:
            self._cp.readfp(StringIO(DEFAULT_CONF))
        self.Read()

    def Read(self, filename=None):
        "read config"
        if (filename is not None and
            (os.path.exists(filename) and
             os.path.isfile(filename))):
            ret = self._cp.read(filename)
            if len(ret) == 0:
                time.sleep(0.1)
                self._cp.read(filename)
            self.filename = filename

        # process sections
        for sect, ordered in self.__sects.items():
            if not self._cp.has_section(sect):
                continue
            thissect = {}
            opt_keys = self._cp.options(sect)
            if ordered:
                thissect = OrderedDict()
                opt_keys.sort()
            for opt in opt_keys:
                val = self._cp.get(sect, opt)
                if '||' in val:
                    words = [i.strip() for i in val.split('||')]
                    label = words.pop(0)
                    if len(words) == 1:
                        words = words[0]
                    else:
                        tmp = []
                        for w in words:
                            if ',' in w and '=' in w:
                                tmp.append(opts2dict(w))
                            else:
                                tmp.append(w)
                        words = tuple(tmp)
                    thissect[label] = words
                else:
                    thissect[opt] = val
                setattr(self, sect, thissect)
        for key, val in self.positioners.items():
            fi = []
            if isinstance(val, (list, tuple)):
                for v in val:
                    if '.' not in v: v = '%s.VAL' % v
                    fi.append(v)
            else:
                if '.' not in val:
                    val = '%s.VAL' % val
                fi = [val, val]
            self.positioners[key] = tuple(fi)

    def Save(self, fname=None):
        "save config file"
        if fname is not None:
            self.filename = fname
        if fname is None:
            fname = self.filename = DEF_CONFFILE
            path, fn = os.path.split(fname)
            if not os.path.exists(path):
                os.makedirs(path, mode=0o755)

        out = ['### %s: %s' % (TITLE, get_timestamp())]
        for sect, ordered in self.__sects.items():
            out.append('#------------------------------#\n[%s]' % sect)
            if sect in ('setup', 'server', 'slewscan', 'xafs'):
                for name, val in self.setup.items():
                    out.append("%s = %s" % (name, val))
#.........这里部分代码省略.........
开发者ID:pyepics,项目名称:stepscan,代码行数:103,代码来源:station_config.py

示例15: InstrumentConfig

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import options [as 别名]
class InstrumentConfig(object):
    basename = 'epics_insts'
    sections = ('dbs',)

    def __init__(self, name=None):
        self.conffile = name
        if name is None:
            self.conffile = os.path.join(get_appdir(self.basename),
                                         'config.ini')
        self.conf = {}
        self.cp =  ConfigParser()
        self.read()

    def read(self):
        for s in self.sections:
            self.conf[s] = {}
        if not os.path.exists(self.conffile):
            self.cp.readfp(StringIO(default_config))
        self.cp.read(self.conffile)

        for sect in self.sections:
            if self.cp.has_section(sect):
                for opt in self.cp.options(sect):
                    if opt is None:
                        continue
                    self.conf[sect][opt] = self.cp.get(sect, opt)

    def write(self, fname=None):
        if fname is None:
            fname = self.conffile
        out = []
        for sect in self.sections:
            out.append('[%s]\n' % sect)
            if sect == 'dbs':
                maxcount = 10
            if sect in self.conf:
                count = 0
                for key in sorted(self.conf[sect]):
                    val = self.conf[sect][key]
                    if count < maxcount:
                        out.append('%s = %s\n' % (key, val))
                        count += 1

        fout = open(fname, 'w')
        fout.writelines(out)
        fout.close()

    def get_dblist(self):
        dblist = [self.conf['dbs'].get('most_recent', '')]
        for key in sorted(self.conf['dbs'].keys()):
            val = self.conf['dbs'][key]
            if val is None: continue
            val = val.strip()
            if (key != 'most_recent' and len(val) > 0):
                dblist.append(val)
        return dblist

    def set_current_db(self, dbname):
        dblist = self.get_dblist()
        idx = 1
        newlist = [dbname]
        for name in dblist:
            if len(name.strip()) > 0 and name not in newlist:
                key = 'v%2.2i' % idx
                self.conf['dbs'][key] = name
                idx += 1

        self.conf['dbs']['most_recent'] = dbname
开发者ID:pyepics,项目名称:epicsapps,代码行数:70,代码来源:configfile.py


注:本文中的six.moves.configparser.ConfigParser.options方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。