python配置解析模块ConfigParser

前言

今天学习github上的开源项目NebulaSolarDash,初步接触到python中的配置文件解析模块ConfigParser,该模块主要是使配置文件生效,并修改和读取配置文件信息。此配置文件与windows下的 ini 文件相似,相关配置采用键值对的形式,可以是 “:” ,也可以是 “=” 形式的,总体来说和centos系列的yum配置文件相似。
部分信息有转载,侵删!!!

# test.conf
[base]  # 配置名 section
host = yt1   # host 就是键或者叫做选项 option
ip = 192.168.231.200
# 或者
ip: 192.168.231.200

ConfigParser模块之ConfigParser方法

NOTE: 在python3.x中该模块被修改为 configparser 了。

1、读取信息
.read(filename) 直接读取ini文件内容

.sections() 得到所有的section,并以列表的形式返回

.options(section) 得到该section的所有option

.items(section) 得到该section的所有键值对

.get(section,option) 得到section中option的值,返回为string类型

.getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。

2、添加修改信息

.add_section(section) 添加一个新的section

.set( section, option, value) 对section中的option进行设置,需要调用write将内容写入配置文件。

这里我主要关注的是read()方法和get()方法。
其中get()方法语法:

ConfigParser.get(section, option[, raw[, vars]])

参数说明:

  • section 配置名
  • option 选项名
  • raw bool类型 可选参数,默认为False
  • vars dict类型 可选参数 其实就是设定键的值,并且在raw参数为False前提下,匹配相应的值可参考:侵删

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

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

import ConfigParser
cf = ConfigParser.ConfigParser() # 初始化
cf.read("test.conf") # 读取配置文件
print cf.get("base", "host").decode('utf-8')
print cf.get("base", "ip").decode('utf-8')

输出:

PS C:\Project\python> python .\test.py
yt1   # host 就是键或者叫做选项 option
192.168.231.200

猜你喜欢

转载自blog.csdn.net/csdn_kerrsally/article/details/80614758