ConfigParser模块模块功能
ConfigParser模块用来处理指定格式的文件(文件名称一般为xxx.ini)。配置文件的格式如下:
- 中括号“[ ]”内包含的为section。
section 下面为类似于key-value 的配置内容。
示例:config.ini文件
# HOST为第一个节点;
[HOST]
# HOST1为第一个节点中的key值,等号后面时对应的value值;
HOST1 = 172.25.254.1:root:123
HOST2 = 172.25.254.2:root:123
HOST3 = 172.25.254.3:root:123
# SCRIPTS为第二个节点;
[SCRIPTS]
SCRIPTS1 = scripts/test1.sh
SCRIPTS2 = scripts/test2.sh
# UPLOADS_REMOTE_DIR为第三个节点;
[UPLOADS_REMOTE_DIR]
REMOTE_DIR = /mnt/upload/
# DOWNLOADS_REMOTE_DIR为第四个节点;
[DOWNLOADS_REMOTE_DIR]
REMOTE_DIR = /mnt/download/
# db为第五个节点;
[db]
db_port = 3306
db_user = root
db_host = 127.0.0.1
db_pass = westos
ConfigParser模块的初始工作
- 实例化;
- 读取配置文件;
In [1]: import ConfigParser #在ipython环境中导入模块;
# 实例化对象
In [2]: conf = ConfigParser.ConfigParser()
# 读取配置文件的内容;
In [3]: conf.read("config.ini")
Out[3]: ['config.ini']
模块的常用方法
查看节点
# 获取所有的节点(sections),返回列表类型;
In [4]: conf.sections()
Out[4]: ['HOST', 'SCRIPTS', 'UPLOADS_REMOTE_DIR', 'DOWNLOADS_REMOTE_DIR', 'db']
# 获取指定节点下的所有键值对;
In [6]: conf.items("HOST")
Out[6]:
[('host1', '172.25.254.1:root:123'),
('host2', '172.25.254.2:root:123'),
('host3', '172.25.254.3:root:123')]
# 获取指定节点下的所有key值;
In [9]: conf.options("HOST")
Out[9]: ['host1', 'host2', 'host3']
# 按照指定类型获取指定节点下,指定的key对应的value值;
In [10]: conf.get("db","db_port")
Out[10]: '3306'
In [11]: conf.getint("db","db_port")
Out[11]: 3306
检查节点与key
# 检查文件中是否存在某个节点。如果存在,返回True;否则,返回False;
In [12]: conf.has_section("db")
Out[12]: True
In [13]: conf.has_section("port")
Out[13]: False
# 检查文件中的某个节点(eg:db节点)是否存在某个key(eg:db_pass);如果存在,返回True;否则,返回False;
In [16]: conf.has_option("db","db_pass")
Out[16]: True
In [17]: conf.has_option("db","db_passwd")
Out[17]: False
添加节点与key
# 添加指定的节点(eg:info节点);
In [18]: conf.add_section("info")
# 往节点里面添加对应的key-value值;
In [19]: conf.set("info","username","root")
In [20]: conf.set("info","password","westos")
# 将添加的内容真正写入文件中;
In [21]: conf.write(open("config.ini","w"))
删除节点与key
# 删除指定节点中的key值;如果成功删除,返回True,否则,返回False;
In [22]: conf.remove_option("info","password")
Out[22]: True
In [23]: conf.remove_option("info","username")
Out[23]: True
# 删除指定的节点;
In [25]: conf.remove_section("info")
Out[25]: True
# 将删除的内容在文件中真正删除;
In [26]: conf.write(open("config.ini","w"))
项目代码中的应用
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Name: confRead.py
Date: 2017-08-16
Author: lvah
Contact:976131979@qq.com
Desc:实现一个配置文件读取模块,支持两种方式,一种是类的形式,一种是函数形式;
"""
import sys
import ConfigParser
#类的形式
class Config:
def __init__(self, path):
self.path = path
self.cf = ConfigParser.ConfigParser()
self.cf.read(self.path)
def get(self, field, key):
result = ""
try:
result = self.cf.get(field, key)
except:
print "cannot find the value for: [%s:%s]" % (field,key)
result = ""
return result
def set(self, filed, key, value):
try:
self.cf.set(field, key, value)
cf.write(open(self.path,'w'))
except:
print "write configure failed!"
return False
return True
#函数形式
def read_config(config_file_path, field, key):
cf = ConfigParser.ConfigParser()
try:
cf.read(config_file_path)
result = cf.get(field, key)
except:
print "cannot find the value for: [%s:%s]" % (field,key)
sys.exit(1)
return result
#读取该Section下的所有键值对
def read_configBySection(config_file_path, field):
cf = ConfigParser.ConfigParser()
try:
cf.read(config_file_path)
result = cf.items(field)
except:
print "cannot find the section for: [%s]" % (field)
sys.exit(1)
return result
def write_config(config_file_path, field, key, value):
cf = ConfigParser.ConfigParser()
try:
cf.read(config_file_path)
cf.set(field, key, value)
cf.write(open(config_file_path,'w'))
except:
sys.exit(1)
return True
if __name__ == "__main__":
config_file_path = 'config.ini'
#从配置文件中读取路径参数
hosts = read_configBySection(config_file_path, 'HOST')
print hosts