python ConfigParser模块get方法简介

ConfigParser模块get官方文档解释如下:
The ConfigParser class extends some methods of the RawConfigParser interface, adding some optional arguments.

ConfigParser.get(section, option[, raw[, vars]])
Get an option value for the named section. If vars is provided, it must be a dictionary. The option is looked up in vars (if provided), section, and in defaults in that order.

All the '%' interpolations are expanded in the return values, unless the raw argument is true. Values for interpolation keys are looked up in the same manner as the option.

ConfigParser.items(section[, raw[, vars]])
Return a list of (name, value) pairs for each option in the given section. Optional arguments have the same meaning as for the get() method.

New in version 2.3.

简单来说就是:获取命名部分的选项值
ConfigParser.get(section,option [,raw [,vars]])
section 配置名
option 选项名
raw bool类型 可选参数,默认为False
vars dict类型 可选参数

如果提供了vars 那么获取配置选项值得规则如下
先在vars中寻找,如果找到就使用vars中的值
如果找不到 就是用默认值
前提是raw的值是False

以下是测试代码

文件test.conf内容如下

[Section1]
foo=%(bar)s is %(baz)s!
baz=fun
bar=Python

测试代码:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import ConfigParser
import string, os
cf = ConfigParser.ConfigParser()
cf.read("test.conf")
res = cf.get('Section1', 'foo')
print "默认情况下, raw=False, 此时输出 %s" % res
res = cf.get('Section1', 'foo', raw=False)
print "raw=False, 无参数vars 此时等同于默认输出:%s" % res
res = cf.get('Section1', 'foo', raw=True)
print "raw=True, 无参数vars 此时等输出未被匹配原字符:%s" % res
res = cf.get('Section1', 'foo', raw=False, vars={'bar': 'Documentation','baz': 'evil'})
print "raw=False, vars存在 此时使用vars中的值进行匹配:%s" % res
res = cf.get('Section1', 'foo', raw=True, vars={'bar': 'Documentation', 'baz':'sdsd'})
print "raw=True, vars存在 此时vars不生效,输出未被匹配原字符:%s" % res
res = cf.get('Section1', 'foo', raw=False, vars={'bar': 'Documentation'})
print "raw=True, vars存在,但只包含一个值, 此时另一个值取默认匹配值,输出未:%s" % res

输出如下

 

转载于:https://www.cnblogs.com/nixiaocang/p/6624882.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值