标签:
[root@docker2 ~]# cat test.ini
[base]
host = 192.168.88.121
port = 3306
user = root
path = /home
passwd = 123
[callback]
path = /Autops
alert = yes
count = 1
ftp = no
>>> cf.read("test.ini") #读取配置文件
[‘test.ini‘]
>>> cf.sections() #片段名
[‘base‘, ‘callback‘]
>>> cf.options("callback") #配置key值/配置项
[‘path‘, ‘alert‘, ‘count‘, ‘ftp‘]
>>> cf.items("callback") #配置选项和值
[(‘path‘, ‘/Autops‘), (‘alert‘, ‘yes‘), (‘count‘, ‘1‘), (‘ftp‘, ‘no‘)]
>>> cf.get("base","port")
‘3306‘
>>> cf.get("base","passwd") #没有的key的会报错
Traceback (most recent call last):
ConfigParser.NoOptionError: No option ‘passwd‘ in section: ‘base‘
>>> cf.set("base","passwd","123") #设定选项,key可以时不存在的
>>> cf.write(open("test.ini","w")) #写入配置文件
>>> cf.getint(‘base‘,‘port‘) #直接读出int型,但value必须可以转成int
3306
>>> cf.getfloat(‘base‘,‘port‘)
3306.0
>>> cf.getboolean(‘callback‘,‘alert‘) #0/no/false/off都视为False,
#1/yes/true/on视为True
True
>>> cf.getboolean(‘callback‘,‘count‘)
True
[DEFAULT]
dbn=mysql
user=root
[base]
user = autops
>>> cf.get(‘base‘,‘user‘)
‘autops‘
>>> cf.get(‘base‘,‘dbn‘)
‘mysql #dbn的值是default里的
[DEFAULT]
conn_str=%(dbn)s -u%(user)s -p%(passwd)s %(db)s
dbn=mysql
user=root
host = 192.168.88.121
port = 3306
[db1]
port = 3307
user = root
db = autops
passwd = 123
[db2]
user = monitor
db = monitor
passwd = 123
结果:
>>> cf.get("db1","conn_str")
‘mysql -uroot -p123 autops‘
>>> cf.get("db2","conn_str")
‘mysql -umonitor -p123 monitor
标签:
原文地址:http://www.cnblogs.com/wxl-dede/p/4998840.html