Python ConfigParser模块

来自linux中国网wiki
跳到导航 跳到搜索

2024

In [3]: import configparser

In [8]: cf =configparser.ConfigParser(allow_no_value=True)

In [9]: cf.read('my.cnf')
Out[9]: ['my.cnf']

In [10]: cf.section()


In [11]: cf.sections()
Out[11]: ['client', 'mysqld']


In [12]: cf.has_section('client')
Out[12]: True

In [13]: cf.options('client')
Out[13]: ['port', 'user', 'password', 'host']

In [14]: cf.get('client','host')
Out[14]: '127.0.0.1'

ConfigParser

Configuration file parser
Python ConfigParser模块解析的配置文件的格式就如ini的配置文件格式,就是文件中由多个section构成,每个section下又有多个配置项
例子文件 如下 

cat test.conf
[db]    
db_host=192.168.1.1   
db_port=3306   
db_user=root   
db_pass=password   
[concurrent]    
thread=200   
processor=400 

假设上面的配置文件的名字为test.conf。里面包含两个section,一个是db, 另一个是concurrent, db , 在py3 叫  configparser

>>> import  ConfigParser,string,os,sys
>>> cf = ConfigParser.ConfigParser()
>>> cf.read("test.conf")
['test.conf']

# 返回所有的section 
>>> s = cf.sections()
>>> print 'section:', s
section: ['db', 'concurrent']
>>> o  = cf.options("db")
>>> print 'options:', s
options: ['db', 'concurrent']
>>> cf.items("db")
[('db_host', '192.168.1.1'), ('db_port', '3306'), ('db_user', 'root'), ('db_pass', 'password')]

#可以按照类型读取出来
>>> cf.get("db","db_host")
'192.168.1.1'
>>> cf.getint("db","db_port")
3306
>>> cf.get("db","db_port")
'3306'

# 返回的是整型的 
#concuree 中的 thread的值 
>>> cf.getint("concurrent","thread")
200

#修改一个值,再写回去    
>>> cf.set("db","db_pass","evan")
>>> cf.write(open("test.conf","w"))
$ cat test.conf  | grep db_pass
db_pass = evan

#添加一个section。(同样要写回)  
>>> cf.add_section('perl')
>>> cf.set('perl','int','15')
>>> cf.set('perl','bool','True')
>>> cf.set('perl','foo','%(bar)s is %(baz)s!')
>>> cf.write(open("test.conf","w"))
结果 
tail  test.conf 
[perl]
int = 15
bool = True
foo = %(bar)s is %(baz)s!

#移除section 或者option 。(只要进行了修改就要写回的哦)
>>> cf.remove_option('perl','int')
True
>>> cf.write(open("test.conf","w"))
tail test.conf
[perl]
bool = True
foo = %(bar)s is %(baz)s!

参考

ConfigParser — Configuration file parser