@(python)
前言
将代码中的配置项抽取到配置文件中,修改配置时不需要涉及到代码修改,避免面对一堆令人抓狂的 magic number,极大的方便后期软件的维护。
python 本身提供标准的配置读写模块 configParse(python2,python3 修改为configparser),用于读取 ini 格式的配置文件。
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
[topsecret.server.com]
Port = 50022
ForwardX11 = no
除了标准库提供的模块,通过第三方模块 pyYAML, 可以读写 yaml1式的配置文件。
本文介绍 python 通过 configParser 和 pyYAML 读写配置文件的方法。
configParser
Note The ConfigParser module has been renamed to configparser in Python 3. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.
python2 和 python3 中此模块有些许不同,旧代码可以通过工具进行转换。
目前来说,python2 在项目中仍有使用,所以以下对在 python2 和 python3 下模块的使用都进行介绍。
python2 - ConfigParser
在ConfigParser 中提供了三个类:
* RawConfigParser
* ConfigParser
* SafeConfigParser
三个以此在前者的基础进行扩展,接口提供额外可选参数,提供更加复杂的功能,主要差别应该体现在对 %(value_name)s
进行参数替换(value_name 为同section或者[DEFAULT]中的其他变量名才行)
这里使用的默认配置文件 default.cfg 内容如下:
[DEFAULT]
default_name = lcd
[Section1]
an_int = 15
a_bool = true
a_float = 3.1415
baz = fun
bar = Python
foo = %(bar)s is %(baz)s!
name = s1_%(default_name)s ; DEFAULT section's value
基本读写
使用 RawConfigParser 实现配置文件的基本的读写操作。
import ConfigParser
test_cfg = "./default.cfg"
config_raw = ConfigParser.RawConfigParser()
config_raw.read(test_cfg)
# 读取配置文件中 [DEFAULT]
defaults = config_raw.defaults()
print defaults
# 读取指定section下的value值
a_float = config_raw.getfloat('Section1', 'a_float')
print "-- number : %f type is : %s"%(a_float ,type(a_float))
# 设置指定section下的value值
# 此时没有写入文件,保存在内存实例中
a_float = 2.14159
config_raw.set('Section1', 'a_float', a_float)
a_float = config_raw.getfloat('Section1', 'a_float')
print "-- number : %f type is : %s"%(a_float ,type(a_float))
# 读取带有参数替换模板的变量,但是没有替换参数
print "-- RawConfigParser just get raw value"
str_foo = config_raw.get('Section1', 'foo')
print str_foo
对应不同数据类型,除了调用get()
获取配置文件中的原始内容,还可以使用对应的接口,getint, getboolean
, 其中,布尔值 True 对应的是 1、yes、true 和 on, False 对应 0、no、false 和 off。
运行结果
OrderedDict([('default_name', 'lcd')])
-- number : 3.141500 type is : <type