ConfigParser

basic

1
2
3
4
5
6
7
8
9
10
11
12
13
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('example.cfg')
# Set the third, optional argument of get to 1 if you wish to use raw mode.
print config.get('Section1', 'foo', 0) # -> "Python is fun!"
print config.get('Section1', 'foo', 1) # -> "%(bar)s is %(baz)s!"
# The optional fourth argument is a dict with members that will take
# precedence in interpolation.
print config.get('Section1', 'foo', 0, {'bar': 'Documentation',
'baz': 'evil'})

advanced

getboolean()

getboolean() 可以将值转换为布尔值。

如:

1
2
[section1]
option1 = 0

当调用 getboolean(‘section1’, ‘option1’),返回 False。
yes/no、true/false、on/off 会进行相应转换。

[DEFAULT]

当读取的配置项不在指定节中,会到 [DEFAULT] 节中查找

ConfigParser 支持字符串格式化

format.conf 如下所示

1
2
3
4
5
6
7
8
9
10
11
[DEFAULT]
conn_str = %(dbn)s://%(pw)s@%(host)s:%(port)s/%(db)s
dbn = mysql
user = root
host = localhost
port = 3306
[db1]
user = aaa
pw = ppp
db = example

python 脚本:

1
2
3
4
import ConfigParser
conf = ConfigParser.ConfigParser()
conf.read('format.conf')
print conf.get('db1', 'conn_str')

运行脚本,输出

1
mysql://aaa:ppp@localhost:3306/example

tips

  • 可以使用 # 或 ; 对config 文件进行注释