pythonConfigParser学习
【安装】
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()
2. 获取所有sections。也就是将配置⽂件中所有“[ ]”读取到列表中:
s = cf.sections()
float()函数
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. 要么包含在pt 语句中,主动捕获异常
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
('db_root', 'host') # 127.0.0.1 ('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()
  ad(config_file)
  config = {}
  for session in parser.sections(): #循环解析每⼀个section
    sessionValue = {} #把每⼀个section下对应的所有配置都存放到⼀个字典⾥
    for option in parser.options(session): #循环解析每⼀个section下的每⼀个option
      sessionValue[option] = (session, option).strip()
    config[session] = sessionValue #最后把所有的section(字典)再存放到⼀个⼤的字典⾥
  return config
print configParser('../')
print configParser('../').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