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


Python RawConfigParser.items方法代码示例

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


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

示例1: import_library

# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import items [as 别名]
def import_library(libfilepointer):
    """
    Import a units library, replacing any existing definitions.

    Parameters
    ----------
    libfilepointer : file
        new library file to work with

    Returns
    -------
    ConfigParser
        newly updated units library for the module
    """
    global _UNIT_LIB
    global _UNIT_CACHE
    _UNIT_CACHE = {}
    _UNIT_LIB = ConfigParser()
    _UNIT_LIB.optionxform = _do_nothing
    _UNIT_LIB.readfp(libfilepointer)
    required_base_types = ['length', 'mass', 'time', 'temperature', 'angle']
    _UNIT_LIB.base_names = list()
    # used to is_angle() and other base type checking
    _UNIT_LIB.base_types = dict()
    _UNIT_LIB.unit_table = dict()
    _UNIT_LIB.prefixes = dict()
    _UNIT_LIB.help = list()

    for prefix, factor in _UNIT_LIB.items('prefixes'):
        factor, comma, comment = factor.partition(',')
        _UNIT_LIB.prefixes[prefix] = float(factor)

    base_list = [0] * len(_UNIT_LIB.items('base_units'))

    for i, (unit_type, name) in enumerate(_UNIT_LIB.items('base_units')):
        _UNIT_LIB.base_types[unit_type] = i
        powers = list(base_list)
        powers[i] = 1
        # print '%20s'%unit_type, powers
        # cant use add_unit because no base units exist yet
        _new_unit(name, 1, powers)
        _UNIT_LIB.base_names.append(name)

    # test for required base types
    missing = [utype for utype in required_base_types
               if utype not in _UNIT_LIB.base_types]
    if missing:
        raise ValueError('Not all required base type were present in the'
                         ' config file. missing: %s, at least %s required'
                         % (missing, required_base_types))

    # Explicit unitless 'unit'.
    _new_unit('unitless', 1, list(base_list))
    _update_library(_UNIT_LIB)
    return _UNIT_LIB
开发者ID:samtx,项目名称:OpenMDAO,代码行数:57,代码来源:units.py

示例2: _merge_from_file

# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import items [as 别名]
    def _merge_from_file(self, config_file):
        """
        Merge variables from ``config_file`` into the environment.

        Any variables in ``config_file`` that have already been set will be
        ignored (meaning this method will *not* try to override them, which
        would raise an exception).

        If ``config_file`` does not exist or is not a regular file, or if there
        is an error parsing ``config_file``, ``None`` is returned.

        Otherwise this method returns a ``(num_set, num_total)`` tuple
        containing first the number of variables that were actually set, and
        second the total number of variables found in ``config_file``.

        This method will raise a ``ValueError`` if ``config_file`` is not an
        absolute path.  For example:

        >>> env = Env()
        >>> env._merge_from_file('my/config.conf')
        Traceback (most recent call last):
          ...
        ValueError: config_file must be an absolute path; got 'my/config.conf'

        Also see `Env._merge()`.

        :param config_file: Absolute path of the configuration file to load.
        """
        if path.abspath(config_file) != config_file:
            raise ValueError(
                'config_file must be an absolute path; got %r' % config_file
            )
        if not path.isfile(config_file):
            return
        parser = RawConfigParser()
        try:
            parser.read(config_file)
        except ParsingError:
            return
        if not parser.has_section(CONFIG_SECTION):
            parser.add_section(CONFIG_SECTION)
        items = parser.items(CONFIG_SECTION)
        if len(items) == 0:
            return (0, 0)
        i = 0
        for (key, value) in items:
            if key not in self:
                self[key] = value
                i += 1
        if 'config_loaded' not in self: # we loaded at least 1 file
            self['config_loaded'] = True
        return (i, len(items))
开发者ID:icute1349,项目名称:freeipa,代码行数:54,代码来源:config.py

示例3: convert_config_to_tribler71

# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import items [as 别名]
def convert_config_to_tribler71(current_config, state_dir=None):
    """
    Convert the Config files libtribler.conf and tribler.conf to the newer triblerd.conf and cleanup the files
    when we are done.

    :param: current_config: the current config in which we merge the old config files.
    :return: the newly edited TriblerConfig object with the old data inserted.
    """
    state_dir = state_dir or TriblerConfig.get_default_state_dir()
    libtribler_file_loc = os.path.join(state_dir, "libtribler.conf")
    if os.path.exists(libtribler_file_loc):
        libtribler_cfg = RawConfigParser()
        libtribler_cfg.read(libtribler_file_loc)
        current_config = add_libtribler_config(current_config, libtribler_cfg)
        os.remove(libtribler_file_loc)

    tribler_file_loc = os.path.join(state_dir, "tribler.conf")
    if os.path.exists(tribler_file_loc):
        tribler_cfg = RawConfigParser()
        tribler_cfg.read(tribler_file_loc)
        current_config = add_tribler_config(current_config, tribler_cfg)
        os.remove(tribler_file_loc)

    # We also have to update all existing downloads, in particular, rename the section 'downloadconfig' to
    # 'download_defaults'.
    for _, filename in enumerate(iglob(
            os.path.join(state_dir, STATEDIR_DLPSTATE_DIR, '*.state'))):
        download_cfg = RawConfigParser()
        try:
            with open(filename) as cfg_file:
                download_cfg.readfp(cfg_file, filename=filename)
        except MissingSectionHeaderError:
            logger.error("Removing download state file %s since it appears to be corrupt", filename)
            os.remove(filename)

        try:
            download_items = download_cfg.items("downloadconfig")
            download_cfg.add_section("download_defaults")
            for download_item in download_items:
                download_cfg.set("download_defaults", download_item[0], download_item[1])
            download_cfg.remove_section("downloadconfig")
            with open(filename, "w") as output_config_file:
                download_cfg.write(output_config_file)
        except (NoSectionError, DuplicateSectionError):
            # This item has already been converted
            pass

    return current_config
开发者ID:Tribler,项目名称:tribler,代码行数:50,代码来源:config_converter.py

示例4: remotebuild

# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import items [as 别名]
def remotebuild():
    builder = Builder()

    try:
        opts, args = getopt(argv[1:], "c:g:hi:k:o:p:r:s:V:",
                            ["config=", "security-group=", "security-groups=",
                             "securitygroup=", "securitygroups=", "help",
                             "instance-profile-name=", "instance-profile=",
                             "instanceprofilename=", "instanceprofile-name=",
                             "key-name=", "keyname=", "key=", "os=",
                             "profile=", "region=", "subnet-id=", "subnet=",
                             "volume-size="])
    except GetoptError as e:
        print(str(e), file=stderr)
        remotebuild_usage()
        return 1

    for opt, value in opts:
        if opt in ("-c", "--config"):
            cp = RawConfigParser()
            cp.read([value])
            for opt, value in cp.items("dist.kanga.org"):
                parse_remotebuild_option(builder, opt, value)
        else:
            try:
                parse_remotebuild_option(builder, opt, value)
            except StopIteration:
                return 0
            except ValueError as e:
                print(str(e), file=stderr)
                remotebuild_usage()
                return 1

    if len(builder.os_ids) == 0:
        print("No OS ids specified for building.", file=stderr)
        return 1

    builder.build_all()

    return 0
开发者ID:dacut,项目名称:dist.kanga.org,代码行数:42,代码来源:remote.py

示例5: _merge_from_file

# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import items [as 别名]
    def _merge_from_file(self, config_file):
        """
        Merge variables from ``config_file`` into the environment.

        Any variables in ``config_file`` that have already been set will be
        ignored (meaning this method will *not* try to override them, which
        would raise an exception).

        If ``config_file`` does not exist or is not a regular file, or if there
        is an error parsing ``config_file``, ``None`` is returned.

        Otherwise this method returns a ``(num_set, num_total)`` tuple
        containing first the number of variables that were actually set, and
        second the total number of variables found in ``config_file``.

        Also see `Env._merge()`.

        :param config_file: Path of the configuration file to load.
        """
        if not path.isfile(config_file):
            return None
        parser = RawConfigParser()
        try:
            parser.read(config_file)
        except ParsingError:
            return None
        if not parser.has_section(CONFIG_SECTION):
            parser.add_section(CONFIG_SECTION)
        items = parser.items(CONFIG_SECTION)
        if len(items) == 0:
            return 0, 0
        i = 0
        for (key, value) in items:
            if key not in self:
                self[key] = value
                i += 1
        if 'config_loaded' not in self: # we loaded at least 1 file
            self['config_loaded'] = True
        return i, len(items)
开发者ID:npmccallum,项目名称:freeipa,代码行数:41,代码来源:config.py

示例6: load_config

# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import items [as 别名]

#.........这里部分代码省略.........
    cfdir = environ.get('koji.hub.ConfigDir', '/etc/koji-hub/hub.conf.d')
    if cfdir:
        configs = koji.config_directory_contents(cfdir)
    else:
        configs = []
    if cf and os.path.isfile(cf):
        configs.append(cf)
    if configs:
        config = RawConfigParser()
        config.read(configs)
    else:
        config = None
    cfgmap = [
        #option, type, default
        ['DBName', 'string', None],
        ['DBUser', 'string', None],
        ['DBHost', 'string', None],
        ['DBhost', 'string', None],   # alias for backwards compatibility
        ['DBPort', 'integer', None],
        ['DBPass', 'string', None],
        ['KojiDir', 'string', None],

        ['AuthPrincipal', 'string', None],
        ['AuthKeytab', 'string', None],
        ['ProxyPrincipals', 'string', ''],
        ['HostPrincipalFormat', 'string', None],

        ['DNUsernameComponent', 'string', 'CN'],
        ['ProxyDNs', 'string', ''],

        ['CheckClientIP', 'boolean', True],

        ['LoginCreatesUser', 'boolean', True],
        ['KojiWebURL', 'string', 'http://localhost.localdomain/koji'],
        ['EmailDomain', 'string', None],
        ['NotifyOnSuccess', 'boolean', True],
        ['DisableNotifications', 'boolean', False],

        ['Plugins', 'string', ''],
        ['PluginPath', 'string', '/usr/lib/koji-hub-plugins'],

        ['KojiDebug', 'boolean', False],
        ['KojiTraceback', 'string', None],
        ['VerbosePolicy', 'boolean', False],
        ['EnableFunctionDebug', 'boolean', False],

        ['LogLevel', 'string', 'WARNING'],
        ['LogFormat', 'string', '%(asctime)s [%(levelname)s] m=%(method)s u=%(user_name)s p=%(process)s r=%(remoteaddr)s %(name)s: %(message)s'],

        ['MissingPolicyOk', 'boolean', True],
        ['EnableMaven', 'boolean', False],
        ['EnableWin', 'boolean', False],

        ['RLIMIT_AS', 'string', None],
        ['RLIMIT_CORE', 'string', None],
        ['RLIMIT_CPU', 'string', None],
        ['RLIMIT_DATA', 'string', None],
        ['RLIMIT_FSIZE', 'string', None],
        ['RLIMIT_MEMLOCK', 'string', None],
        ['RLIMIT_NOFILE', 'string', None],
        ['RLIMIT_NPROC', 'string', None],
        ['RLIMIT_OFILE', 'string', None],
        ['RLIMIT_RSS', 'string', None],
        ['RLIMIT_STACK', 'string', None],

        ['MemoryWarnThreshold', 'integer', 5000],
        ['MaxRequestLength', 'integer', 4194304],

        ['LockOut', 'boolean', False],
        ['ServerOffline', 'boolean', False],
        ['OfflineMessage', 'string', None],
    ]
    opts = {}
    for name, dtype, default in cfgmap:
        key = ('hub', name)
        if config and config.has_option(*key):
            if dtype == 'integer':
                opts[name] = config.getint(*key)
            elif dtype == 'boolean':
                opts[name] = config.getboolean(*key)
            else:
                opts[name] = config.get(*key)
            continue
        opts[name] = default
    if opts['DBHost'] is None:
        opts['DBHost'] = opts['DBhost']
    # load policies
    # (only from config file)
    if config and config.has_section('policy'):
        #for the moment, we simply transfer the policy conf to opts
        opts['policy'] = dict(config.items('policy'))
    else:
        opts['policy'] = {}
    for pname, text in six.iteritems(_default_policies):
        opts['policy'].setdefault(pname, text)
    # use configured KojiDir
    if opts.get('KojiDir') is not None:
        koji.BASEDIR = opts['KojiDir']
        koji.pathinfo.topdir = opts['KojiDir']
    return opts
开发者ID:mikem23,项目名称:koji-playground,代码行数:104,代码来源:kojixmlrpc.py

示例7: import

# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import items [as 别名]
from trollsched.satpass import Pass
from trollsched.drawing import save_fig
from trollsched import (SATELLITE_NAMES, INSTRUMENT)

LOG = logging.getLogger(__name__)

CFG_DIR = os.environ.get('PYTROLL_SCHEDULE_CONFIG_DIR', './')
CONF = RawConfigParser()
CFG_FILE = os.path.join(CFG_DIR, "pytroll_schedule_config.cfg")
LOG.debug("Config file = " + str(CFG_FILE))
if not os.path.exists(CFG_FILE):
    raise IOError('Config file %s does not exist!' % CFG_FILE)

CONF.read(CFG_FILE)
OPTIONS = {}
for option, value in CONF.items("DEFAULT"):
    OPTIONS[option] = value


#: Default time format
_DEFAULT_TIME_FORMAT = '%Y-%m-%d %H:%M:%S'

#: Default log format
_DEFAULT_LOG_FORMAT = '[%(levelname)s: %(asctime)s : %(name)s] %(message)s'


def process_xmlrequest(filename, plotdir, output_file, excluded_satellites):

    tree = ET.parse(filename)
    root = tree.getroot()
开发者ID:pytroll,项目名称:pytroll-schedule,代码行数:32,代码来源:generate_schedule_xmlpage.py


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