python ConfigParser 学习

【安装】
ConfigParser 是解析配置文件的第三方库,需要安装 pip install ConfigParser
 
【介绍】
ConfigParser 是用来读取配置文件(可以是.conf, .txt, .init 等格式)的包。
配置文件的格式如下:中括号“[ ]”内包含的为section。 section 下面为为option, 类似于key-value 的配置内容。
如下,[ ]内包含的 db 和 concurrent 为 section, db_host 等为option
 
[db]
db_host = 127.0.0.1
db_port = 22
db_user = root
db_pass = rootroot
 
[concurrent]
thread = 10
processor = 20
 
注意: key = value 和 key:value 两种形式都可以
 
【常见函数】
-read(filename) 直接读取配置文件内容
-sections() 得到所有的section,并以列表的形式返回
-options(section) 得到该section的所有option
-items(section) 得到该section的所有键值对
-get(section,option) 得到section中option的值,返回为string类型
-getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。
 
【用法】
1. ConfigParser 初始工作
使用ConfigParser 首选需要初始化实例,并读取配置文件:
import ConfigParser
cf = ConfigParser.ConfigParser()
cf.read("配置文件名")
 
2. 获取所有sections。也就是将配置文件中所有“[ ]”读取到列表中:
s = cf.sections()
print 'section:', s
 
将输出(以下将均以简介中配置文件为例):section: ['db', 'concurrent']
 
3. 获取指定section 的options。即将配置文件某个section 内key 读取到列表中:
o = cf.options("db")
print 'options:', o
将输出:
options: ['db_host', 'db_port', 'db_user', 'db_pass']
 
4. 获取指定section 的所有配置信息。返回列表,列表的元素是key,value 组成的元组。 (用起来不方便)
v = cf.items("db")
print 'db:', v
将输出:
db: [('db_host', '127.0.0.1'), ('db_port', '22'), ('db_user', 'root'), ('db_pass', 'rootroot')]
 
5. 按照类型读取指定section 的option 信息。同样的还有getint、getfloat、getboolean。
#可以通过get(section,option)
db_host = cf.get("db", "db_host")
db_port = cf.getint("db", "db_port")
db_user = cf.get("db", "db_user")
db_pass = cf.get("db", "db_pass")
 
# 按照类型读取出来
threads = cf.getint("concurrent", "thread")
processors = cf.getint("concurrent", "processor")
 
print "db_host:", db_host
print "db_port:", db_port
print "db_user:", db_user
print "db_pass:", db_pass
print "thread:", threads
print "processor:", processors
将输出:
db_host: 127.0.0.1
db_port: 22
db_user: root
db_pass: rootroot
thread: 10
processor: 20
 
注: 当查找不到指定的 section 或者 option 时,会抛出异常:
raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'dbs'
 
raise NoOptionError(option, section)
ConfigParser.NoOptionError: No option 'db_hosts' in section: 'db'
 
所以,在用 get(section,option) (getint,getfloat,getboolean 同) 时:
a. 要么包含在try...except 语句中,主动捕获异常
b. 要么先判断是否有该指定的 section 或 option:
if parser.has_section('section'): #判断 section 是否存在
dosomething
 
if parser.has_option('section','option'): #判断 option 是否存在
dosomething
 
6. 设置默认值 DEFAULT
如果配置文件中存在一个名为 DEFAULT (只能全部大写) 的 section,那么其他 section 会扩展它的 option 并且可以覆盖它的 option
 
[DEFAULT]
host = 127.0.0.1
port = 3306 [db_root]
user = root
pass = root
 
 
[db_huey]
host = 192.168.1.101
user = huey
pass = huey
 
print cp.get('db_root', 'host') # 127.0.0.1 print cp.get('db_huey', 'host') # 192.168.1.101
 
注意:当查询所有 sections 时, 显示只有两个, 即没有 DEFAULT 这个section
查询 section 里的options 时, 则多显示了两个, 即每个section 都会扩张 DEFAULT的 options
如 print parser.options('db_root')
则输出为 ['user ','pass','host','port']
 
=========================================================================================
封装成以字典返回的函数:
def configParser(config_file):
  parser = ConfigParser.ConfigParser()
  parser.read(config_file)
  config = {}
  for session in parser.sections(): #循环解析每一个section
    sessionValue = {} #把每一个section下对应的所有配置都存放到一个字典里
    for option in parser.options(session): #循环解析每一个section下的每一个option
      sessionValue[option] = parser.get(session, option).strip()
    config[session] = sessionValue #最后把所有的section(字典)再存放到一个大的字典里
  return config
print configParser('../config.txt')
print configParser('../config.txt').get('db').get('db_host')
 
输出:
{
'concurrent': {'processor': '20', 'thread': '10'},
'db': {'db_pass': 'rootroot', 'db_user': 'root', 'db_host': '127.0.0.1', 'db_port': '22'}
}
127.0.0.1
 
原文地址:https://www.cnblogs.com/tomweng/p/6776205.html