#!/usr/bin/env python3
# -*- coding= UTF-8 -*-
# name=
# version=0.0.1
# packages=
# author=singebogo
# author_email=singbogo@163.com
# date=20180209
# description= 新建ini addSection set write
# 读取ini getSection
# 修改ini
import os,ConfigParser
from new_frame.api.filegener.path.moudlesyspath import MouldeAddSysPath
from new_frame.api.filegener.fileoperator.filebase import FileBase
from new_frame.util.logutil.log import logger
class IniConfig(object):
'''对ini配置文件进行,
新建
传入参数:{section:(key:value,key1:value1,...),section:(key:values, key1:value1,...)} 数据解析类
查询
getSection
getOption
getInt
getFloat
getString
getBoolean
删除
delSection
delOption
添加
addSection
addOption
'''
def __init__(self, configdir):
'''
@param configdir:
'''
self.__cfp = ConfigParser.ConfigParser()
self.__configdir = configdir.strip()
def setConfigDir(self, configdir=''):
'''
@param configdir:
@return:
'''
if configdir is None:
pass
self.__configdir = configdir.strip()
def getConfigDir(self):
return self.__configdir
# 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!".
# get('Section1', 'foo', 0, {'bar': 'Documentation', 'baz': 'evil'})
'''
res = config.get('Section1', 'foo')
print "默认情况下, raw=False, 此时输出 %s" % res
res = config.get('Section1', 'foo', raw=False)
print "raw=False, 无参数vars 此时等同于默认输出:%s" % res
res = config.get('Section1', 'foo', raw=True)
print "raw=True, 无参数vars 此时等输出未被匹配原字符:%s" % res
res = config.get('Section1', 'foo', raw=False, vars={'bar': 'Documentation','baz': 'evil'})
print "raw=False, vars存在 此时使用vars中的值进行匹配:%s" % res
res = config.get('Section1', 'foo', raw=True, vars={'bar': 'Documentation', 'baz':'sdsd'})
print "raw=True, vars存在 此时vars不生效,输出未被匹配原字符:%s" % res
res = config.get('Section1', 'foo', raw=False, vars={'bar': 'Documentation'})
print "raw=True, vars存在,但只包含一个值, 此时另一个值取默认匹配值,输出未:%s" % res
'''
def getStr(self, section, option, raw=False, vars=None):
'''
@param section:
@param option:
@param raw:
@param vars:
@return:
'''
try:
self.__cfp.read(self.__configdir)
if self.__cfp.has_section(section):
if self.__cfp.has_option(section, option):
return self.__cfp.get(section, option, raw, vars)
return None
else:
return None
except IOError as ioerr:
logger.error("%s getStr Error"%(ioerr))
return None
def getInt(self, section, option):
'''
@param section:
@param option:
@return:
'''
try:
self.__cfp.read(self.__configdir)
if self.__cfp.has_section(section):
if self.__cfp.has_option(section, option):
return self.__cfp.getint(section, option)
return None
else:
return None
except IOError as ioerr:
logger.error("%s getInt Error"%(ioerr))
return None
def getFloat(self, section, option):
'''
@param section:
@param option:
@return:
'''
try:
self.__cfp.read(self.__configdir)
if self.__cfp.has_section(section):
return self.__cfp.getfloat(section, option)
else:
return None
except IOError as ioerr:
logger.error("%s getFloat error"%(ioerr))
return None
def getBoolean(self, section, option):
'''
@param section:
@param option:
@return:
'''
try:
self.__cfp.read(self.__configdir)
if self.__cfp.has_section(section):
return self.__cfp.getboolean(section, option)
else:
return None
except IOError as ioerr:
logger.error("%s getBoolean Error"%(ioerr))
return None
def getSections(self):
'''
@return:
'''
try:
self.__cfp.read(self.__configdir)
return self.__cfp.sections()
except IOError as ioerr:
logger.warning("%s get Section Error", ioerr)
return None
def getOptions(self, section):
'''
@param section:
@return: 返回列表
'''
try:
self.__cfp.read(self.__configdir)
if self.__cfp.has_section(section):
return self.__cfp.options(section)
else:
return None
except IOError as ioerr:
logger.warning("%s get Section Error", ioerr)
return None
def getItems(self, section, raw=False, vars=None):
try:
self.__cfp.read(self.__configdir)
if self.__cfp.has_section(section):
return self.__cfp.items(section, raw, vars)
else:
return None
except IOError as ioerr:
logger.warning("%s get Section Error", ioerr)
return None
def mvSection(self, section):
'''
@param section: 删除的section 其item也会一并删除
@return:
'''
try:
self.__cfp.read(self.__configdir)
if self.__cfp.has_section(section):
self.__cfp.remove_section(section)
self.save("r+")
return True
else:
return False
except IOError as ioerr:
logger.warning("%s remove Section Error", ioerr)
return False
def updateSection(self, oldsection, newsection):
'''
@param oldsection:
@param newsection:
@return:
'''
try:
self.__cfp.read(self.__configdir)
if self.__cfp.has_section(oldsection):
items = self.getItems(oldsection)
self.__cfp.remove_section(oldsection)
self.__cfp.add_section(newsection)
for item in items:
self.addOption(newsection, item[0], item[1])
self.save()
return True
else:
return False
except IOError as ioerr:
logger.warning("%s remove Section Error", ioerr)
return False
def mvOption(self, section, option):
'''
@param section: 更改section
@param option: 更改option
@param value: 更改value
@return: 修改成功 返回True, 修改失败和无section和option 返回False
'''
try:
self.__cfp.read(self.__configdir)
if self.__cfp.has_section(section):
if self.__cfp.has_option(section, option):
self.__cfp.remove_option(section, option)
self.save()
return True
else:
return False
else:
return False
except IOError as ioerr:
logger.warning("%s mvOption option Error", ioerr)
return False
def updateOption(self, section, option, value):
'''
@param section: 更改section
@param option: 更改option
@param value: 更改value
@return: 修改成功 返回True, 修改失败和无section和option 返回False
'''
try:
self.__cfp.read(self.__configdir)
if self.__cfp.has_section(section):
if self.__cfp.has_option(section, option):
self.__cfp.set(section, option, value)
self.save()
return True
else:
return False
else:
return False
except IOError as ioerr:
logger.warning("%s updateOption option Error", ioerr)
return False
def addSection(self, section):
'''
@param section:
@return:
'''
if not self.__cfp.has_section(section):
return self.__cfp.add_section(section)
else:
return False
def addOption(self, section, option, value):
'''
@param section:
@param option:
@return:
'''
if not self.__cfp.has_section(section):
if not self.__cfp.has_option(section, option):
return self.__cfp.set(section, option, value)
else:
return False
else:
return False
def save(self, mode='wb'):
'''
Writing our configuration file to 'example.cfg'
文件存在则覆盖(文件覆盖,内容覆盖),不存在则创建
@return:
'''
try:
with open(self.__configdir, mode) as configfile:
return self.__cfp.write(configfile)
except IOError as ioerr:
logger.error("%s save %s Error"%(ioerr, self.__configdir))
return False
# 添加数据
def add(self, section, option=None, value=None):
'''
添加数据并且实时保存
@param section 判断是否存在,存在则不添加
@param option:为空的情况下,只增加section
@param value:
@return:
'''
try:
self.__cfp.read(self.__configdir)
if not self.__cfp.has_section(section):
self.addSection(section)
if option is None:
pass
else:
self.__cfp.set(section, option, value)
#self.__cfp.write(open(self.__configdir, "r+"))
self.save(mode='r+')
return True
except Exception as err:
print (err.message)
return False
def getAll(self):
'''
@return: #返回格式:{section:(key:value,key1:value1,...),section:(key:values, key1:value1,...)}
'''
self.__cfp.read(self.__configdir)
dict = {}
sections = self.getSections()
for section in sections:
itemdict = {}
for item in self.getItems(section):
itemdict.setdefault(item[0], item[1])
dict.setdefault(section, itemdict)
return dict
# {'web': {'url': 'http://www.baidu.com', 'login': 'baidu'}, 'DB': {'dbtype': 'MySql', 'ip': '192.168.0.100', 'port': '3360'}, 'Dasebase1': {'dbtype': 'MySql', 'ip': '192.168.0.100', 'login': 'baidu', 'url': 'http://www.baidu.com', 'port': '3360'}}
# 该字典 拆解病生成ini文件
def importDict(self, dict={}):
'''
@param dict: #返回格式:{section:(key:value,key1:value1,...),section:(key:values, key1:value1,...)}
@return:
'''
if len(dict) == 0:
return False
else:
keys = dict.keys()
if keys is not None:
for key in keys:
self.addSection(key)
itemdict = dict.get(key)
if itemdict is not None:
for item in itemdict:
self.addOption(key, item, itemdict.get(item))
else:
return False
else:
return False
self.save()
return True
if __name__ == '__main__':
inicfg = IniConfig(os.path.join(MouldeAddSysPath().getConfigFile(),"test.ini"))
#print (inicfg.__doc__)
#print (inicfg.setConfigDir())
# print (inicfg.getConfigDir())
# print (inicfg.addSection("DB"))
# print (inicfg.addSection("web"))
# print (inicfg.addOption("DB", "dbtype","MySql"))
# print (inicfg.addOption("DB", "ip","192.168.0.100"))
# print (inicfg.addOption("DB", "port",3360))
# print (inicfg.addOption("web", "url","http://www.baidu.com"))
# print (inicfg.addOption("web", "Login", "baidu"))
# print (inicfg.save())
#print (inicfg.getOptions("web"))
#items = inicfg.getItems("DB")
#print (items)
#for item in items:
# print (item[0] + ":" + item[1])
#print (inicfg.updateOption("DB", "ip", "10.2.128.255"))
#print (inicfg.updateOption("DB", "ip1", "10.2.128.255"))
#print (inicfg.mvOption("web", "login"))
#print (inicfg.mvSection("web"))
#print (inicfg.updateSection("DB", "db"))
#print (inicfg.addOption("WEB", "url", "http://www.baidu.com"))
#print (inicfg.addOption("WEB", "Login", "baidu"))
#print (inicfg.save())
# print (inicfg.add("Dasebase1"))
# print (inicfg.add("Dasebase1", "dbtype","MySql"))
# print (inicfg.add("Dasebase1", "ip","192.168.0.100"))
# print (inicfg.add("Dasebase1", "port",3360))
# print (inicfg.add("Dasebase1", "url","http://www.baidu.com"))
# print (inicfg.add("Dasebase1", "Login", "baidu"))
dictall = inicfg.getAll()
inicfg.setConfigDir(os.path.join(MouldeAddSysPath().getConfigFile(), "test2.ini"))
print (inicfg.importDict(dict=dictall))
1.10、ini配置文件
最新推荐文章于 2022-07-21 16:07:43 发布