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=funbar=Python
测试代码:
#!/usr/bin/env python# -*- coding:utf-8 -*-import ConfigParserimport string, oscf = ConfigParser.ConfigParser()cf.read("test.conf")res = cf.get('Section1', 'foo')print "默认情况下, raw=False, 此时输出 %s" % resres = cf.get('Section1', 'foo', raw=False)print "raw=False, 无参数vars 此时等同于默认输出:%s" % resres = cf.get('Section1', 'foo', raw=True)print "raw=True, 无参数vars 此时等输出未被匹配原字符:%s" % resres = cf.get('Section1', 'foo', raw=False, vars={ 'bar': 'Documentation','baz': 'evil'})print "raw=False, vars存在 此时使用vars中的值进行匹配:%s" % resres = cf.get('Section1', 'foo', raw=True, vars={ 'bar': 'Documentation', 'baz':'sdsd'})print "raw=True, vars存在 此时vars不生效,输出未被匹配原字符:%s" % resres = cf.get('Section1', 'foo', raw=False, vars={ 'bar': 'Documentation'})print "raw=True, vars存在,但只包含一个值, 此时另一个值取默认匹配值,输出未:%s" % res
输出如下