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


Python SafeConfigParser.sections方法代码示例

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


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

示例1: __init__

# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import sections [as 别名]
    def __init__(self):
        here = os.path.dirname(__file__)
        self.filename = os.path.join(here, self._filename)

        parser = SafeConfigParser()
        parser.getlist = lambda s, o: parser.get(s, o).split()
        parser.getlines = lambda s, o: [l.strip() for l in parser.get(s, o).splitlines() if l.strip()]
        found = parser.read(self.filename)
        if not found:
            raise RuntimeError('failed to read app config %r' % self.filename)

        getters = {}
        for attr, options in self._getters.items():
            getters.update(dict.fromkeys(options, getattr(parser, attr)))

        def items(section):
            for o in parser.options(section):
                yield o, getters.get(o, parser.get)(section, o)

        kwargs = [dict([('name', section)] + list(items(section)))
            for section in parser.sections()]
        apps = [App(**kw) for kw in kwargs]

        # some consistency checks: names and ports must be unique to make it
        # possible to deploy each app on each server.
        names = [app.name for app in apps]
        ports = [app.port for app in apps]
        assert len(names) == len(set(names))
        assert len(ports) == len(set(ports))

        super(Config, self).__init__((app.name, app) for app in apps)
开发者ID:clld,项目名称:clldfabric,代码行数:33,代码来源:config.py

示例2: Config

# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import sections [as 别名]
class Config(object):

    def __init__(self):
        self.config = SafeConfigParser()
        self.name = ''

    def parse(self, fname, override):
        if override:
            override = [x for x in csv.reader(
                ' '.join(override).split(','), delimiter='.')]

        logger.info('Reading configuration file: {}'.format(fname))
        if not os.path.isfile(fname):
            logger.interrupt('File doesn\'t exist: {}'.format(fname))
        self.config.optionxform = str
        self.config.read(fname)
        for section, option, value in override:
            if not self.config.has_section(section):
                self.config.add_section(section)
            self.config.set(section, option, value)

        basename = os.path.basename(fname)
        self.name = os.path.splitext(basename)[0]

    @safe
    def _get_options_as_dict(self, section):
        if section in self.config.sections():
            return {p: v for p, v in self.config.items(section)}
        else:
            return {}
开发者ID:mahesh152,项目名称:perfrunner,代码行数:32,代码来源:settings.py

示例3: read_config_file

# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import sections [as 别名]
def read_config_file(config_file_path):
    # type: (str) -> None
    parser = SafeConfigParser()
    parser.read(config_file_path)

    for section in parser.sections():
        bots_config[section] = {
            "email": parser.get(section, 'email'),
            "key": parser.get(section, 'key'),
            "site": parser.get(section, 'site'),
        }
开发者ID:JamesLinus,项目名称:zulip,代码行数:13,代码来源:bot_server.py

示例4: read

# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import sections [as 别名]
def read(config_path):
    config_path = os.path.abspath(config_path)
    config_root = os.path.split(config_path)[0]
    parser = SafeConfigParser()
    success = parser.read(config_path)
    assert config_path in success, success

    subns = {"pwd": os.path.abspath(os.path.curdir)}

    rv = OrderedDict()
    for section in parser.sections():
        rv[section] = ConfigDict(config_root)
        for key in parser.options(section):
            rv[section][key] = parser.get(section, key, False, subns)

    return rv
开发者ID:Honry,项目名称:web-platform-tests,代码行数:18,代码来源:config.py

示例5: read_ini

# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import sections [as 别名]
    def read_ini(cls, path, section=None):
        """read preferences from an .ini file"""

        parser = ConfigParser()
        parser.optionxform = str
        parser.readfp(mozfile.load(path))

        if section:
            if section not in parser.sections():
                raise PreferencesReadError("No section '%s' in %s" % (section, path))
            retval = parser.items(section, raw=True)
        else:
            retval = parser.defaults().items()

        # cast the preferences since .ini is just strings
        return [(i, cls.cast(j)) for i, j in retval]
开发者ID:luke-chang,项目名称:gecko-1,代码行数:18,代码来源:prefs.py

示例6: parse_config_file

# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import sections [as 别名]
def parse_config_file(filename):
    """Parse INI files containing IMAP connection details.

    Used by livetest.py and interact.py
    """

    parser = SafeConfigParser(get_string_config_defaults())
    with open(filename, 'r') as fh:
        parser.readfp(fh)

    conf = _read_config_section(parser, "DEFAULT")
    if conf.expect_failure:
        raise ValueError("expect_failure should not be set for the DEFAULT section")

    conf.alternates = {}
    for section in parser.sections():
        conf.alternates[section] = _read_config_section(parser, section)

    return conf
开发者ID:nylas,项目名称:imapclient,代码行数:21,代码来源:config.py

示例7: get_scrapycfg_targets

# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import sections [as 别名]
def get_scrapycfg_targets(cfgfiles=None):
    cfg = SafeConfigParser()
    cfg.read(cfgfiles or [])
    baset = dict(cfg.items('deploy')) if cfg.has_section('deploy') else {}
    targets = {}
    targets['default'] = baset
    for x in cfg.sections():
        if x.startswith('deploy:'):
            t = baset.copy()
            t.update(cfg.items(x))
            targets[x[7:]] = t
    for tname, t in list(targets.items()):
        try:
            int(t.get('project', 0))
        except ValueError:
            # Don't import non-numeric project IDs, and also throw away the
            # URL and credentials associated with these projects (since the
            # project ID does not belong to SH, neither do the endpoint or the
            # auth information)
            del targets[tname]
        if t.get('url', "").endswith('scrapyd/'):
            t['url'] = t['url'][:-8]
    targets.setdefault('default', {})
    return targets
开发者ID:scrapinghub,项目名称:shub,代码行数:26,代码来源:utils.py

示例8: PackageConfigHandler

# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import sections [as 别名]
class PackageConfigHandler(object):
    """
    Manager class for packages files for tracking installation of modules
    """

    def __init__(self):
        # noinspection PyUnresolvedReferences
        from six.moves.configparser import SafeConfigParser
        self.package_cfg = os.path.expanduser('~/Documents/site-packages/.pypi_packages')
        if not os.path.isfile(self.package_cfg):
            print('Creating package file')
            with open(self.package_cfg, 'w') as outs:
                outs.close()
        self.parser = SafeConfigParser()
        self.parser.read(self.package_cfg)

    def save(self):
        with open(self.package_cfg, 'w') as outs:
            self.parser.write(outs)

    def add_module(self, pkg_info):
        """

        :param pkg_info: A dict that has name, url, version, summary
        :return:
        """
        if not self.parser.has_section(pkg_info['name']):
            self.parser.add_section(pkg_info['name'])
        self.parser.set(pkg_info['name'], 'url', pkg_info['url'])
        self.parser.set(pkg_info['name'], 'version', pkg_info['version'])
        self.parser.set(pkg_info['name'], 'summary', pkg_info['summary'])
        self.parser.set(pkg_info['name'], 'files', pkg_info['files'])
        self.parser.set(pkg_info['name'], 'dependency', pkg_info['dependency'])
        self.save()

    def list_modules(self):
        return [module for module in self.parser.sections()]

    def module_exists(self, name):
        return self.parser.has_section(name)

    def get_info(self, name):
        if self.parser.has_section(name):
            tbl = {}
            for opt, value in self.parser.items(name):
                tbl[opt] = value
            return tbl

    def remove_module(self, name):
        self.parser.remove_section(name)
        self.save()

    def get_files_installed(self, section_name):
        if self.parser.has_option(section_name, 'files'):
            files = self.parser.get(section_name, 'files').strip()
            return files.split(',')
        else:
            return None

    def get_dependencies(self, section_name):
        if self.parser.has_option(section_name, 'dependency'):
            dependencies = self.parser.get(section_name, 'dependency').strip()
            return set(dependencies.split(',')) if dependencies != '' else set()
        else:
            return None

    def get_all_dependencies(self, exclude_module=()):
        all_dependencies = set()
        for section_name in self.parser.sections():
            if section_name not in exclude_module and self.parser.has_option(section_name, 'dependency'):
                dependencies = self.parser.get(section_name, 'dependency').strip()
                if dependencies != '':
                    for dep in dependencies.split(','):
                        all_dependencies.add(dep)
        return all_dependencies
开发者ID:bron84,项目名称:stash,代码行数:77,代码来源:pip.py

示例9: _parse_args

# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import sections [as 别名]
    def _parse_args(self, args=None):
        self.context.original_begin = time.time()
        self.context.original_args = args if args is not None else sys.argv[1:]
        self.option_parser.disable_interspersed_args()
        try:
            options, args = self.option_parser.parse_args(
                self.context.original_args)
        except UnboundLocalError:
            # Happens sometimes with an error handler that doesn't raise its
            # own exception. We'll catch the error below with
            # error_encountered.
            pass
        self.option_parser.enable_interspersed_args()
        if self.option_parser.error_encountered:
            return None, None
        if options.version:
            self.option_parser.print_version()
            return None, None
        if not args or options.help:
            self.option_parser.print_help()
            return None, None
        self.context.original_main_args = self.context.original_args[
            :-len(args)]

        self.context.conf = {}
        if options.conf is None:
            options.conf = os.environ.get('SWIFTLY_CONF', '~/.swiftly.conf')
        try:
            conf_parser = SafeConfigParser()
            conf_parser.read(os.path.expanduser(options.conf))
            for section in conf_parser.sections():
                self.context.conf[section] = dict(conf_parser.items(section))
        except ConfigParserError:
            pass

        for option_name in (
                'auth_url', 'auth_user', 'auth_key', 'auth_tenant',
                'auth_methods', 'region', 'direct', 'local', 'proxy', 'snet',
                'no_snet', 'retries', 'cache_auth', 'no_cache_auth', 'cdn',
                'no_cdn', 'concurrency', 'eventlet', 'no_eventlet', 'verbose',
                'no_verbose', 'direct_object_ring'):
            self._resolve_option(options, option_name, 'swiftly')
        for option_name in (
                'snet', 'no_snet', 'cache_auth', 'no_cache_auth', 'cdn',
                'no_cdn', 'eventlet', 'no_eventlet', 'verbose', 'no_verbose'):
            if isinstance(getattr(options, option_name), six.string_types):
                setattr(
                    options, option_name,
                    getattr(options, option_name).lower() in TRUE_VALUES)
        for option_name in ('retries', 'concurrency'):
            if isinstance(getattr(options, option_name), six.string_types):
                setattr(
                    options, option_name, int(getattr(options, option_name)))
        if options.snet is None:
            options.snet = False
        if options.no_snet is None:
            options.no_snet = False
        if options.retries is None:
            options.retries = 4
        if options.cache_auth is None:
            options.cache_auth = False
        if options.no_cache_auth is None:
            options.no_cache_auth = False
        if options.cdn is None:
            options.cdn = False
        if options.no_cdn is None:
            options.no_cdn = False
        if options.concurrency is None:
            options.concurrency = 1
        if options.eventlet is None:
            options.eventlet = False
        if options.no_eventlet is None:
            options.no_eventlet = False
        if options.verbose is None:
            options.verbose = False
        if options.no_verbose is None:
            options.no_verbose = False

        self.context.eventlet = None
        if options.eventlet:
            self.context.eventlet = True
        if options.no_eventlet:
            self.context.eventlet = False
        if self.context.eventlet is None:
            self.context.eventlet = False
            try:
                import eventlet
                # Eventlet 0.11.0 fixed the CPU bug
                if eventlet.__version__ >= '0.11.0':
                    self.context.eventlet = True
            except ImportError:
                pass

        subprocess_module = None
        if self.context.eventlet:
            try:
                import eventlet.green.subprocess
                subprocess_module = eventlet.green.subprocess
            except ImportError:
                pass
#.........这里部分代码省略.........
开发者ID:OddBloke,项目名称:swiftly,代码行数:103,代码来源:cli.py

示例10: configparser2yaml

# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import sections [as 别名]
def configparser2yaml(cpfile):
    dict_ = {}
    cp = ConfigParser()

    with codecs.open(cpfile, encoding='utf-8') as fh:
        cp.readfp(fh)

    for section in cp.sections():
        if section.startswith('contact:'):  # contacts are now nested
            if 'contact' not in dict_:
                dict_['contact'] = {}
            section2 = dict_['contact'][section.split(':')[1]] = {}
        elif section.startswith('distribution:'):  # distributions now nested
            if 'distribution' not in dict_:
                dict_['distribution'] = {}
            section2 = dict_['distribution'][section.split(':')[1]] = {}
        else:
            section2 = dict_[section] = {}

        for k, v in cp.items(section):
            if section == 'identification':  # keywords are now nested
                if 'keywords' not in section2:
                    section2['keywords'] = {}
                if 'default' not in section2['keywords']:
                    section2['keywords']['default'] = {}
                if 'gc_cst' not in section2['keywords']:
                    section2['keywords']['gc_cst'] = {}
                if 'wmo' not in section2['keywords']:
                    section2['keywords']['wmo'] = {}
                if 'hnap_category_information' not in section2['keywords']:
                    section2['keywords']['hnap_category_information'] = {}
                if 'hnap_category_geography' not in section2['keywords']:
                    section2['keywords']['hnap_category_geography'] = {}
                if 'hnap_category_content' not in section2['keywords']:
                    section2['keywords']['hnap_category_content'] = {}

            if k in ['topiccategory']:
                section2['topiccategory'] = [v]
            if k in ['keywords_en', 'keywords_fr']:
                section2['keywords']['default'][k] = [k2.strip() for k2 in v.split(',')]  # noqa
            if k in ['keywords_gc_cst_en']:
                section2['keywords']['gc_cst']['keywords_en'] = [k2.strip() for k2 in v.split(',')]  # noqa
            if k in ['keywords_gc_cst_fr']:
                section2['keywords']['gc_cst']['keywords_fr'] = [k2.strip() for k2 in v.split(',')]  # noqa
            if k in ['keywords_wmo']:
                section2['keywords']['wmo']['keywords_en'] = [k2.strip() for k2 in v.split(',')]  # noqa
            if k in ['hnap_category_information_en']:
                section2['keywords']['hnap_category_information']['keywords_en'] = [v]  # noqa
                section2['keywords']['hnap_category_information']['keywords_fr'] = [v]  # noqa
            if k in ['hnap_category_geography_en']:
                section2['keywords']['hnap_category_geography']['keywords_en'] = [v]  # noqa
            if k in ['hnap_category_geography_fr']:
                section2['keywords']['hnap_category_geography']['keywords_fr'] = [v]  # noqa
            if k in ['hnap_category_content_en']:
                section2['keywords']['hnap_category_content']['keywords_en'] = [v]  # noqa
            if k in ['hnap_category_content_fr']:
                section2['keywords']['hnap_category_content']['keywords_fr'] = [v]  # noqa

            if k == 'keywords_type':
                section2['keywords']['default'][k] = v
                section2['keywords']['gc_cst'][k] = v
                section2['keywords']['wmo'][k] = v
                section2['keywords']['hnap_category_geography'][k] = v
                section2['keywords']['hnap_category_information'][k] = v
                section2['keywords']['hnap_category_content'][k] = v

            else:
                section2[k] = v

    return yaml.safe_dump(dict_, default_flow_style=False, allow_unicode=True)
开发者ID:alexandreleroux,项目名称:pygeometa,代码行数:72,代码来源:migrations.py

示例11: IniConfigLoader

# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import sections [as 别名]
class IniConfigLoader(object):
    """This config loader transforms a traditional INI file into
       a Montague Standard Format dictionary. It is compatible with
       most but not all PasteDeploy files."""

    def __init__(self, path):
        self.path = path
        self._data = self._read()
        self._config = self._process()

    def _read(self):
        # We need to keep the parser around so the logging conversion can use it.
        path_defaults = {
            'here': os.path.dirname(self.path),
            '__file__': self.path,
        }
        self._parser = SafeConfigParser()
        self._parser.read(self.path)
        self._globals = self._parser.defaults()
        data = {}
        for section in self._parser.sections():
            section_data = data.setdefault(section, {})
            for option in self._parser.options(section):
                if option in self._globals:
                    continue
                try:
                    section_data[option] = self._parser.get(section, option, vars=path_defaults)
                except InterpolationError:
                    section_data[option] = self._parser.get(section, option, raw=True)
        return data

    def _process(self):
        orig = self._data
        config = {}
        for key in six.iterkeys(orig):
            if ':' in key:
                scheme, name = key.split(':', 1)
                kind_config = config.setdefault(SCHEMEMAP[scheme], {})
                kind_config[name] = orig[key]
            else:
                config[key] = orig[key]
        config['globals'] = {
            'here': os.path.dirname(self.path),
            '__file__': self.path,
        }
        for key, value in six.iteritems(self._globals):
            config['globals'][key] = value
        apps = config.setdefault('application', {})
        filters = config.setdefault('filter', {})
        generated_filter_count = 0
        filter_apps = config.pop('filter-app', {})
        for name, filter_app in six.iteritems(filter_apps):
            use = filter_app.pop('next')
            generated_filter_count += 1
            filter_name = '_montague_filter_{0}'.format(generated_filter_count)
            apps[name] = {'use': use, 'filter-with': filter_name}
            filters[filter_name] = filter_app
        pipelines = config.pop('pipeline', {})
        for name, pipeline in six.iteritems(pipelines):
            items = pipeline['pipeline'].split()
            pipeline_app = items[-1]
            pipeline_filters = items[:-1]
            pipeline_filters.reverse()
            apps[name] = {'use': pipeline_app}
            last_item = apps[name]
            for count, use_filter in enumerate(pipeline_filters, start=1):
                filter_name = '_montague_pipeline_{0}_filter_{1}'.format(name, count)
                filters[filter_name] = {'use': use_filter}
                last_item['filter-with'] = filter_name
                last_item = filters[filter_name]
        if all([self._parser.has_section(section_name) for section_name in LOGGING_SECTIONS]):
            loggers = convert_loggers(self._parser)
            handlers = convert_handlers(self._parser)
            formatters = convert_formatters(self._parser)

            config['logging'] = {'main': combine(loggers, handlers, formatters)}

        for key in MSF_KEYS:
            config.setdefault(key, {})
        return config

    def config(self):
        return self._config

    def app_config(self, name):
        # This method isn't actually necessary, since montague can extract
        # the config information from the MSF dict returned by .config()
        # but it's a nice example of how to do it.
        if name in self._config['application']:
            constructor = LoadableConfig.app
            local_config = self._config['application'][name]
        elif name in self._config['composite']:
            constructor = LoadableConfig.composite
            local_config = self._config['composite'][name]
        else:
            raise KeyError
        return constructor(
            name=name, config=local_config, global_config=self._config['globals'])

    def server_config(self, name):
#.........这里部分代码省略.........
开发者ID:inklesspen,项目名称:montague,代码行数:103,代码来源:ini.py


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