本文转至 [余子越的博客](http://www.yuchaoshui.com/) ,文章 [Python 配置文件 ConfigParser 模块](http://www.yuchaoshui.com/post/Python-ConfigParser),欢迎访问[yuchaoshui.com](http://yuchaoshui.com) 了解更多信息!
将程序的配置写到一个统一的配置文件时一个好的做法,ConfigParser 模块给出了很好的方法。
a) 配置文件中包含一个或多个 section, 每个 section 有自己的 option;
b) section 用 [sect_name] 表示,每个option是一个键值对,使用分隔符 = 或 : 隔开;
c) 在 option 分隔符两端的空格会被忽略掉
d) 配置文件使用 # 或者 ; 注释
一、配置文件例子
# database source
[db]
host = 127.0.0.1
port = 3306
user = root
pass = root
# ssh
[ssh]
host = 192.168.1.101
user = huey
pass = huey
二、主程序文件
# python3 中模块
import configparser
cp = configparser.ConfigParser()
# python2 中模块
import ConfigParser
cp = ConfigParser.SafeConfigParser()
cp.read('./etc/server.conf')
三、主要配置及使用方法
cp = configparser.ConfigParser(allow_no_value = True)
# allow_no_value 默认设置成 False,此时如果配置文件中存在没有设置值的option,在读取配置文件时将抛出异常 ConfigParser.ParsingError。
# allow_no_value 设置成 True 时,如果一个 option 没有设置值,has_option 方法会返回 True,get 方法会返回 None。
cp.sections()
# 获取所有区块的列表 ['db', 'ssh']
cp.options('db')
# 获取指定区块的所有选项key ['host', 'port', 'user', 'pass']
cp.items('ssh')
# 获取指定区块的键值对 [('host', '192.168.1.101'), ('user', 'huey'), ('pass', 'huey')]
cp.get('db', 'host')
# 读取指定的配置项内容 '127.0.0.1'
cp.getint('db', 'port')
# 获取指定类型的值,如果类型不符合则会报错。包括 getint、 getfloat 和 getboolean
cp.has_section('db')
# 判断是否有db区块,有则返回True。
cp.has_option('db', 'host')
# 判断db区块是否有host选项,有则返回True。
cp.add_section('hadoop')
# 添加 section
cp.remove_section('db')
# 删除 section
cp.set('db', 'host','192.168.1.122')
# 设置选项的值,但是section必须存在。
cp.remove_option('db', 'host')
# 删除选项
cp.write(open('./etc/myapp.conf', 'w'))
# 写入文件
cp.write(sys.stdout)
# 向屏幕打印配置文件信息
# 这些操作set、 remove_option、 add_section 和 remove_section 并不会修改配置文件,write 方法可以将 ConfigParser 对象的配置写到文件中
[DEFAULT]
# 默认选项,必须是大写。当某一区块 [server] 没有某一个选项时,而在 [DEFAULT] 里面有这个选项,那么当从 [server] 获取不存在的一个选项时,该值会从 [DEFAULT] 区块里面读取。
本文转至 [余子越的博客](http://www.yuchaoshui.com/) ,文章 [Python 配置文件 ConfigParser 模块](http://www.yuchaoshui.com/post/Python-ConfigParser),欢迎访问[yuchaoshui.com](http://yuchaoshui.com) 了解更多信息!