ConfigParser中的items方法raw和vars参数

最近在学习Python,学习到读取配置文件这一项。

对ConfigParser中的items方法的后两个参数非常疑惑,遂help()

>>> help(cfg.items)
Help on method items in module ConfigParser:

items(self, section, raw=False, vars=None) method of ConfigParser.ConfigParser instance
    Return a list of tuples with (name, value) for each option
    in the section.
    
    All % interpolations are expanded in the return values, based on the
    defaults passed into the constructor, unless the optional argument
    `raw' is true.  Additional substitutions may be provided using the
    `vars' argument, which must be a dictionary whose contents overrides
    any pre-existing defaults.
    
    The section DEFAULT is special.

然后,还是看不懂ORZ~

得了,自己实验吧!得出了一些结果,在这里记录,也供他人参考,如有不对之处,还望各路大神斧正指点。


首先,新建一个配置文件

#实验用配置文件

[change]
canChange = %(person)s is very good ;格式%(可替换的值)类型,比如string为s

可以看到,在change下有一个key为canChange。

canChange中,使用%替换一个名为person的key。

我们知道,如果[change]中或者[DEFAULT]中存在person则”%(person)“会被替换,但是配置文件中并没有提供这个person。


然后,编码读取这个配置文件

# -*- coding:utf-8 -*-
import ConfigParser

cfg = ConfigParser.ConfigParser()
cfg.read('D:/WORKTEST/Python/testConfig.txt')#读取配置文件

sessionList = cfg.sections ()

for se in sessionList:
    print se

    #print cfg.items(se) #直接报错
    print cfg.items(se,1,{'person':'cty'})
    print cfg.items(se,0,{'person':'cty'})
    print cfg.items(se,0,{'human':'cty'})


输出:


==================== RESTART: D:\WORKTEST\Python\test.py ====================
change
[('canchange', '%(person)s is very good'), ('person', 'cty')]
[('canchange', 'cty is very good'), ('person', 'cty')]


Traceback (most recent call last):
  File "D:\WORKTEST\Python\test.py", line 15, in <module>
    print cfg.items(se,0,{'human':'cty'})
  File "C:\WORK\Python\python27\lib\ConfigParser.py", line 655, in items
    for option in options]
  File "C:\WORK\Python\python27\lib\ConfigParser.py", line 669, in _interpolate
    option, section, rawval, e.args[0])
InterpolationMissingOptionError: Bad value substitution:
section: [change]
option : canchange
key    : person
rawval : %(person)s is very good


分析:


可以看到,for循环中有5个print:

第一个print输出session的名称,即change

第二个print被注释了,因为其运行直接报错,找不到需要替换的person

第三个print,items中 -- raw参数为1(也就是true) ; vars为{'person':'cty'} ; 输出[('canchange', '%(person)s is very good'), ('person', 'cty')]

表明,在raw为true的情况下,忽略%的替换语法,直接输出

第四个print,items中 -- raw参数为0(也就是false) ; vars为{'person':'cty'} ;输出[('canchange', 'cty is very good'), ('person', 'cty')]

表明,在raw为false的情况下,vars中包含要替换的key,%语法中的内容被替换

第五个print,不用解释了吧,不存在可替换的person而是什么human,自然报错了


到此,大致弄清楚了这两个参数的功用


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值