1.10、ini配置文件

#!/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))










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
纯c读写ini配置文件 用c/c++读写ini配置文件有不少第三方的开源库,如iniparser、libini、rwini、UltraLightINIParser等,但都不理想,往往代码较大、功能较弱、 接口使用不方便。尤其在大小写处理、前后空格、各种注释、跨平台换行符支持、带引号字符串处理、无section操作、原格式保持等方面存在问题。 现将本人精心制作的ini读写程序源码奉献给大家,纯c编写,简洁好用。支持windows和linux。 主要特点: 1、支持;和#注释符号,支持行尾注释。 2、支持带引号'或"成对匹配的字符串,提取时自动去引号。引号中可带其它引号或;#注释符。 3、支持无section或空section(名称为空)。 4、支持10、16、8进制数,0x开头为16进制数,0开头为8进制。 5、支持section、key或=号前后带空格。 6、支持\n、\r、\r\n或\n\r换行格式。 7、不区分section、key大小写,但写入时以新串为准,并保持其大小写。 8、新增数据时,若section存在则在该节最后一个有效数据后添加,否则在文件尾部添加。 9、支持指定key所在整行删除,即删除该键值,包括注释。 10、可自动跳过格式错误行,修改时仍然保留。 11、修改时保留原注释:包括整行注释、行尾注释(包括前面空格)。 12、修改时保留原空行。以上三点主要是尽量保留原格式。 不足之处: 1、不支持单key多value(逗号分割),只能一次性提取后自行处理。 2、不支持同名重复section和key。(重复section可视为错误,重复key则可能造成分歧) 3、不能提取所有section或key名称。 使用只需两个文件inirw.h、inirw.c,另有测试程序和工程文件,支持windows和linux。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值