• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python configparser.RawConfigParser类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: __init__

    def __init__(self, **kw):
        cfg_path = kw.pop('cfg', None) \
            or os.path.join(APP_DIRS.user_config_dir, 'config.ini')
        cfg_path = os.path.abspath(cfg_path)

        RawConfigParser.__init__(self)

        if os.path.exists(cfg_path):
            assert os.path.isfile(cfg_path)
            self.read(cfg_path)
        else:
            self.add_section('service')
            for opt in 'url user password'.split():
                self.set('service', opt, kw.get(opt, '') or '')
            self.add_section('logging')
            self.set('logging', 'level', 'INFO')

            config_dir = os.path.dirname(cfg_path)
            if not os.path.exists(config_dir):
                try:
                    os.makedirs(config_dir)
                except OSError:  # pragma: no cover
                    # this happens when run on travis-ci, by a system user.
                    pass
            if os.path.exists(config_dir):
                with open(cfg_path, 'w') as fp:
                    self.write(fp)
        level = self.get('logging', 'level', default=None)
        if level:
            logging.basicConfig(level=getattr(logging, level))
开发者ID:ioverka,项目名称:pycdstar,代码行数:30,代码来源:config.py


示例2: CredentialStore

class CredentialStore(object):
    def __init__(self, **kwargs):
        self.credential_search_path = [
            os.path.join(os.path.sep, "etc", "cbdefense", "credentials"),
            os.path.join(os.path.expanduser("~"), ".cbdefense", "credentials"),
            os.path.join(".", ".cbdefense", "credentials"),
        ]

        if "credential_file" in kwargs:
            if isinstance(kwargs["credential_file"], six.string_types):
                self.credential_search_path = [kwargs["credential_file"]]
            elif type(kwargs["credential_file"]) is list:
                self.credential_search_path = kwargs["credential_file"]

        self.credentials = RawConfigParser(defaults=default_profile)
        self.credential_files = self.credentials.read(self.credential_search_path)

    def get_credentials(self, profile=None):
        credential_profile = profile or "default"
        if credential_profile not in self.get_profiles():
            raise CredentialError("Cannot find credential profile '%s' after searching in these files: %s." %
                                  (credential_profile, ", ".join(self.credential_search_path)))

        retval = {}
        for k, v in six.iteritems(default_profile):
                retval[k] = self.credentials.get(credential_profile, k)
		
        if not retval["api_key"] or not retval["conn_id"] or not retval["cbd_api_url"]:
            raise CredentialError("API Key and Connector ID not available for profile %s" % credential_profile)

        return Credentials(retval)

    def get_profiles(self):
        return self.credentials.sections()
开发者ID:bigblueswope,项目名称:python-projects,代码行数:34,代码来源:auth.py


示例3: set

 def set(self, section, option, new_value):
     with self.lock:
         if self.callback and self.has_section(section) and self.has_option(section, option):
             old_value = self.get(section, option)
             if not self.callback(section, option, new_value, old_value):
                 raise OperationNotPossibleAtRuntimeException
         RawConfigParser.set(self, section, option, new_value)
开发者ID:Tribler,项目名称:tribler,代码行数:7,代码来源:configparser.py


示例4: _fetchAzureAccountKey

def _fetchAzureAccountKey(accountName):
    """
    Find the account key for a given Azure storage account.

    The account key is taken from the AZURE_ACCOUNT_KEY_<account> environment variable if it
    exists, then from plain AZURE_ACCOUNT_KEY, and then from looking in the file
    ~/.toilAzureCredentials. That file has format:

    [AzureStorageCredentials]
    accountName1=ACCOUNTKEY1==
    accountName2=ACCOUNTKEY2==
    """
    try:
        return os.environ['AZURE_ACCOUNT_KEY_' + accountName]
    except KeyError:
        try:
            return os.environ['AZURE_ACCOUNT_KEY']
        except KeyError:
            configParser = RawConfigParser()
            configParser.read(os.path.expanduser(credential_file_path))
            try:
                return configParser.get('AzureStorageCredentials', accountName)
            except NoOptionError:
                raise RuntimeError("No account key found for '%s', please provide it in '%s'" %
                                   (accountName, credential_file_path))
开发者ID:chapmanb,项目名称:toil,代码行数:25,代码来源:azureJobStore.py


示例5: __init__

    def __init__(self, name, default=None, **kw):
        """Initialization.

        :param name: Basename for the config file (suffix .ini will be appended).
        :param default: Default content of the config file.
        """
        self.name = name
        self.default = default
        config_dir = Path(kw.pop('config_dir', None) or DIR)
        RawConfigParser.__init__(self, kw, allow_no_value=True)
        if self.default:
            if PY3:
                fp = io.StringIO(self.default)
            else:
                fp = io.BytesIO(self.default.encode('utf8'))
            self.readfp(fp)

        cfg_path = config_dir.joinpath(name + '.ini')
        if cfg_path.exists():
            assert cfg_path.is_file()
            self.read(cfg_path.as_posix())
        else:
            if not config_dir.exists():
                try:
                    config_dir.mkdir()
                except OSError:  # pragma: no cover
                    # this happens when run on travis-ci, by a system user.
                    pass
            if config_dir.exists():
                with open(cfg_path.as_posix(), 'w') as fp:
                    self.write(fp)
        self.path = cfg_path
开发者ID:LinguList,项目名称:lingpy,代码行数:32,代码来源:config.py


示例6: __init__

    def __init__(self, name, default=None, **kw):
        """Initialization.

        :param name: Basename for the config file (suffix .ini will be appended).
        :param default: Default content of the config file.
        """
        self.name = name
        self.default = default
        config_dir = kw.pop("config_dir", None) or text_type(DIR)
        RawConfigParser.__init__(self, kw, allow_no_value=True)
        if self.default:
            if PY3:
                fp = io.StringIO(self.default)
            else:
                fp = io.BytesIO(self.default.encode("utf8"))
            self.readfp(fp)

        cfg_path = os.path.join(config_dir, name + ".ini")
        if os.path.exists(cfg_path):
            assert os.path.isfile(cfg_path)
            self.read(cfg_path)
        else:
            if not os.path.exists(config_dir):
                try:
                    os.mkdir(config_dir)
                except OSError:  # pragma: no cover
                    # this happens when run on travis-ci, by a system user.
                    pass
            if os.path.exists(config_dir):
                with open(cfg_path, "w") as fp:
                    self.write(fp)
        self.path = Path(cfg_path)
开发者ID:sflavier,项目名称:lingpy,代码行数:32,代码来源:config.py


示例7: test_read_test_tribler_conf

 def test_read_test_tribler_conf(self):
     """
     Test upgrading a Tribler configuration from 7.0 to 7.1
     """
     old_config = RawConfigParser()
     old_config.read(os.path.join(self.CONFIG_PATH, "tribler70.conf"))
     new_config = TriblerConfig()
     result_config = add_tribler_config(new_config, old_config)
     self.assertEqual(result_config.get_default_safeseeding_enabled(), True)
开发者ID:Tribler,项目名称:tribler,代码行数:9,代码来源:test_config_upgrade_70_71.py


示例8: get_config

 def get_config(self, path):
     """
     Reads entry from configuration.
     """
     section, option = path.split('.', 1)
     filename = os.path.join(self.path, '.hg', 'hgrc')
     config = RawConfigParser()
     config.read(filename)
     if config.has_option(section, option):
         return config.get(section, option).decode('utf-8')
     return None
开发者ID:franco999,项目名称:weblate,代码行数:11,代码来源:vcs.py


示例9: test_read_test_libtribler_conf

 def test_read_test_libtribler_conf(self):
     """
     Test upgrading a libtribler configuration from 7.0 to 7.1
     """
     os.environ['TSTATEDIR'] = self.session_base_dir
     old_config = RawConfigParser()
     old_config.read(os.path.join(self.CONFIG_PATH, "libtribler70.conf"))
     new_config = TriblerConfig()
     result_config = add_libtribler_config(new_config, old_config)
     self.assertEqual(result_config.get_tunnel_community_socks5_listen_ports(), [1, 2, 3, 4, 5, 6])
     self.assertEqual(result_config.get_anon_proxy_settings(), (2, ("127.0.0.1", [5, 4, 3, 2, 1]), ''))
     self.assertEqual(result_config.get_credit_mining_sources(), ['source1', 'source2'])
     self.assertEqual(result_config.get_log_dir(), '/a/b/c')
开发者ID:Tribler,项目名称:tribler,代码行数:13,代码来源:test_config_upgrade_70_71.py


示例10: test_read_test_corr_tribler_conf

    def test_read_test_corr_tribler_conf(self):
        """
        Adding corrupt values should result in the default value.

        Note that this test might fail if there is already an upgraded config stored in the default
        state directory. The code being tested here however shouldn't be ran if that config already exists.
        :return:
        """
        old_config = RawConfigParser()
        old_config.read(os.path.join(self.CONFIG_PATH, "triblercorrupt70.conf"))
        new_config = TriblerConfig()
        result_config = add_tribler_config(new_config, old_config)
        self.assertEqual(result_config.get_default_anonymity_enabled(), True)
开发者ID:Tribler,项目名称:tribler,代码行数:13,代码来源:test_config_upgrade_70_71.py


示例11: get_config

 def get_config(self, path):
     """
     Reads entry from configuration.
     """
     result = None
     section, option = path.split(".", 1)
     filename = os.path.join(self.path, ".hg", "hgrc")
     config = RawConfigParser()
     config.read(filename)
     if config.has_option(section, option):
         result = config.get(section, option)
         if six.PY2:
             result = result.decode("utf-8")
     return result
开发者ID:nijel,项目名称:weblate,代码行数:14,代码来源:vcs.py


示例12: test_upgrade_pstate_files

    def test_upgrade_pstate_files(self):
        """
        Test whether the existing pstate files are correctly updated to 7.1.
        """
        os.makedirs(os.path.join(self.state_dir, STATEDIR_DLPSTATE_DIR))

        # Copy an old pstate file
        src_path = os.path.join(self.CONFIG_PATH, "download_pstate_70.state")
        shutil.copyfile(src_path, os.path.join(self.state_dir, STATEDIR_DLPSTATE_DIR, "download.state"))

        # Copy a corrupt pstate file
        src_path = os.path.join(self.CONFIG_PATH, "download_pstate_70_corrupt.state")
        corrupt_dest_path = os.path.join(self.state_dir, STATEDIR_DLPSTATE_DIR, "downloadcorrupt.state")
        shutil.copyfile(src_path, corrupt_dest_path)

        old_config = RawConfigParser()
        old_config.read(os.path.join(self.CONFIG_PATH, "tribler70.conf"))
        convert_config_to_tribler71(old_config, state_dir=self.state_dir)

        # Verify whether the section is correctly renamed
        download_config = RawConfigParser()
        download_config.read(os.path.join(self.state_dir, STATEDIR_DLPSTATE_DIR, "download.state"))
        self.assertTrue(download_config.has_section("download_defaults"))
        self.assertFalse(download_config.has_section("downloadconfig"))
        self.assertFalse(os.path.exists(corrupt_dest_path))

        # Do the upgrade again, it should not fail
        convert_config_to_tribler71(old_config, state_dir=self.state_dir)
开发者ID:Tribler,项目名称:tribler,代码行数:28,代码来源:test_config_upgrade_70_71.py


示例13: _test_write_pkispawn_config_file

 def _test_write_pkispawn_config_file(self, template, expected):
     """
     Test that the values we read from an ExternalCAProfile
     object can be used to produce a reasonable-looking pkispawn
     configuration.
     """
     config = RawConfigParser()
     config.optionxform = str
     config.add_section("CA")
     config.set("CA", "pki_req_ext_oid", template.ext_oid)
     config.set("CA", "pki_req_ext_data",
                hexlify(template.get_ext_data()).decode('ascii'))
     out = StringIO()
     config.write(out)
     assert out.getvalue() == expected
开发者ID:npmccallum,项目名称:freeipa,代码行数:15,代码来源:test_cainstance.py


示例14: __init__

 def __init__(self, path=expanduser("~/.azkabanrc")):
     self.parser = RawConfigParser()
     self.path = path
     if exists(path):
         try:
             self.parser.read(self.path)
         except ParsingError:
             raise AzkabanError("Invalid configuration file %r.", path)
开发者ID:xiaogaozi,项目名称:azkaban,代码行数:8,代码来源:util.py


示例15: __init__

    def __init__(self):
        self._config = RawConfigParser()
        self._config.optionxform = str

        self._settings = {}
        self._sections = {}
        self._finalized = False
        self.loaded_files = set()
开发者ID:luke-chang,项目名称:gecko-1,代码行数:8,代码来源:config.py


示例16: test_read_test_corr_libtribler_conf

    def test_read_test_corr_libtribler_conf(self):
        """
        Adding corrupt values should result in the default value.

        Note that this test might fail if there is already an upgraded config stored in the default
        state directory. The code being tested here however shouldn't be ran if that config already exists.
        :return:
        """
        old_config = RawConfigParser()
        old_config.read(os.path.join(self.CONFIG_PATH, "libtriblercorrupt70.conf"))
        new_config = TriblerConfig(ConfigObj(configspec=CONFIG_SPEC_PATH))

        result_config = add_libtribler_config(new_config, old_config)

        self.assertTrue(len(result_config.get_tunnel_community_socks5_listen_ports()), 5)
        self.assertEqual(result_config.get_anon_proxy_settings(), (2, ('127.0.0.1', [-1, -1, -1, -1, -1]), ''))
        self.assertEqual(result_config.get_credit_mining_sources(), new_config.get_credit_mining_sources())
开发者ID:Tribler,项目名称:tribler,代码行数:17,代码来源:test_config_upgrade_70_71.py


示例17: update_providers

def update_providers(args, verbose=False):
    filepath = args.data_dir.joinpath('references', 'bibtex', 'BIBFILES.ini')
    p = RawConfigParser()
    with io.open(filepath, encoding='utf-8-sig') as fp:
        p.readfp(fp)

    provider_map = get_map(Provider)
    for section in p.sections():
        sectname = section[:-4] if section.endswith('.bib') else section
        id_ = slug(sectname)
        attrs = {
            'name': p.get(section, 'title'),
            'description': p.get(section, 'description'),
            'abbr': p.get(section, 'abbr'),
        }
        if id_ in provider_map:
            provider = provider_map[id_]
            for a in list(attrs):
                before, after = getattr(provider, a), attrs[a]
                if before == after:
                    del attrs[a]
                else:
                    setattr(provider, a, after)
                    attrs[a] = (before, after)
            if attrs:
                args.log.info('updating provider %s %s' % (slug(id_), sorted(attrs)))
            if verbose:
                for a, (before, after) in attrs.items():
                    before, after = (' '.join(_.split()) for _ in (before, after))
                    if before != after:
                        args.log.info('%s\n%r\n%r' % (a, before, after))
        else:
            args.log.info('adding provider %s' % slug(id_))
            DBSession.add(Provider(id=id_, **attrs))
开发者ID:pombredanne,项目名称:glottolog3,代码行数:34,代码来源:util.py


示例18: read_cfg

 def read_cfg(self):
     parser = RawConfigParser()
     parser.read(self.cfg_file)
     if not parser.has_section('mail'):
         print('Creating cfg file.')
         self.make_cfg()
     
     self.auth     = parser.get('mail','auth')
     self.user     = parser.get('mail','username')
     self.passwd   = parser.get('mail','password')
     self.mailfrom = parser.get('mail','mailfrom')
     self.host     = parser.get('mail','host')
     self.port     = parser.get('mail','port')
     self.tls      = parser.get('mail','tls')
开发者ID:BBOOXX,项目名称:stash,代码行数:14,代码来源:mail.py


示例19: main

def main():
    logging_config = dict(level=INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    if PY2:
        logging_config['disable_existing_loggers'] = True

    basicConfig(**logging_config)

    args = get_args()
    config = RawConfigParser()
    config.read(args.configuration)

    timestamp = datetime.now().strftime("%H:%M:%S")
    machine = gethostname()

    if args.no_stamp:
        message = args.message
    else:
        message = "CNC/{machine} [{timestamp}]: {content}".format(machine=machine,
                                                                  timestamp=timestamp,
                                                                  content=args.message)

    logger.info("Sending message to twitter: %s", message)
    tweet(config.get("TWITTER", "CONSUMER_KEY"),
          config.get("TWITTER", "CONSUMER_SECRET"),
          config.get("TWITTER", "ACCESS_KEY"),
          config.get("TWITTER", "ACCESS_SECRET"),
          message)

    logger.info("Done")
开发者ID:chaddotson,项目名称:pytools,代码行数:30,代码来源:tweet.py


示例20: _parseFile

	def _parseFile(self, cfgpath):
		# add a starting section so it becomes INI format
		try:
			with open(cfgpath) as fp:
				contents = fp.read()
		except IOError:
			LOGGER.error('cannot read %r', cfgpath, exc_info=True)
			return None
		fp = StringIO('[_ROOT_]\n%s' % contents)

		cfg = RawConfigParser()
		try:
			cfg.readfp(fp, cfgpath)
		except Error:
			LOGGER.error('cannot parse %r', cfgpath, exc_info=True)
			return None

		return cfg
开发者ID:hydrargyrum,项目名称:eye,代码行数:18,代码来源:projects.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python configparser.SafeConfigParser类代码示例发布时间:2022-05-27
下一篇:
Python configparser.ConfigParser类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap