Python之自动生成解析ini文件的C++类(基于libiniparser.a)

来源:互联网 发布:数据库查找通配符 编辑:程序博客网 时间:2024/05/21 18:39

## 自动化生成解析ini的C++类


## ini配置文件(config.ini)

[Ku]IP=192.168.64.10Type=16Position=0-cAgentIP=192.168.3.77ReportInterval=2[Server]IP=192.168.3.77Port=7890

## 脚本如下( genCppIniParser.py )

#coding=utf-8import osimport sysimport reimport shutil,stringfrom string import TemplategHearFile = "csettings"gSrcFile = "csettings"gClassName = "CSettings"#[OK]class CObject(object):    def __init__(self):        self._group = ""        self._gList = []        self._gMap = {}    def setGroup(self,group):        self._group = group    def addMember(self,key,value):        self._gList.append(key)        self._gMap[key] = value    ###########################################################################    #   Header File.    #   QString getGroupFiled();    ###########################################################################    def toFunc_Def_List(self):        res = ""        for item in self._gList:            tmp = "%s get%s%s();\n\t" % ("string",self._group.capitalize(),item.capitalize())            res = res + tmp        return res    ###########################################################################    #   Header File.    ###########################################################################    def toFunc_Imp_List(self):        return ""    ###########################################################################    #   Header File.    #   QString m_a;    #   QString m_b;    ###########################################################################    def toVal_Def_List(self):        res = ""        for item in self._gList:            tmp = "%s m_%s%s;\n\t" % ("string",self._group,item.capitalize())            res = res + tmp        return res    ###########################################################################    #   void loadSetting(const QString & fname){    #       m_a = "";    #   }    ###########################################################################    def toFunc_Init_List(self):        res = ""        for item in self._gList:            tmp = "\tm_%s%s = \"\";\n" % (self._group,item.capitalize())            res = res + tmp        res = res + "\n";        return res    ###########################################################################    #   void loadSetting(const QString & fname){    #       m_a = "";    #       m_a = _data.value("a/b").value;    #   }    ###########################################################################    def toFunc_Set_List(self):        res = ""        for item in self._gList:            tmp = "\t_data.getValue(\"%s\",\"%s\",m_%s%s);\n" % (self._group,item,self._group,item.capitalize())            res = res + tmp        return res    ###########################################################################    #   QString getGroupField(){    #       return m_member;    #   }    ###########################################################################    def toFunc_Get_List(self):        res = ""        for item in self._gList:            s1 = "%s %s::get%s%s(){\n" % ("string",gClassName,self._group.capitalize(),item.capitalize())            s2 = "\treturn m_%s%s;\n" % (self._group,item.capitalize())            s3 = "}\n\n"            s = s1 + s2 + s3            res = res + s        return res############################################################################   write string to file.###########################################################################def writeToFile(str,fname):    fp = open(fname,"w+")    fp.write(str)    fp.close()############################################################################   write the result to test.h | test.cpp file.###########################################################################def saveHeadFile(defList,varList):    m_hContent = Template("""/******************************************************************************File name : ${FILE_NAME}.hTile  : Header of the ${CLASS_NAME} class******************************************************************************/#ifndef ${DEF_FILE_NAME}_H#define ${DEF_FILE_NAME}_H#include <string>using namespace std;class ${CLASS_NAME}{public:static ${CLASS_NAME} * getInstance();    void loadFile(const string & name);    /*Getter/Setter*/    ${FUNCTION_DEF_LIST}private:${CLASS_NAME}(){}private:    ${VAR_LIST}};#endif""")    h_str = m_hContent.substitute(DEF_FILE_NAME=gHearFile.upper(),      FILE_NAME=gHearFile,                                  CLASS_NAME=gClassName,                                  FUNCTION_DEF_LIST=defList,                                  VAR_LIST=varList)    writeToFile(h_str,gHearFile + ".h")def saveBodyFile(impList,getList):    m_bContent = Template("""/********************************************************************************  File name : ${FILE_NAME}.cpp*  Title     : Implementation of the ${CLASS_NAME} class*******************************************************************************/#include "${FILE_NAME}.h"#include "inifile.h"#include <unistd.h>using namespace inifile;static ${CLASS_NAME} * g_instance = NULL;${CLASS_NAME} * ${CLASS_NAME}::getInstance(){if ( NULL == g_instance){g_instance = new ${CLASS_NAME}();}return g_instance;}${FUNCTION_IMPL_LIST}${FUNCTION_GET_LIST}""")    b_str = m_bContent.substitute(FILE_NAME=gSrcFile,                                  CLASS_NAME=gClassName,                                  FUNCTION_IMPL_LIST=impList,                                  FUNCTION_GET_LIST=getList)    writeToFile(b_str,gSrcFile + ".cpp")gObjList = []gObj = CObject()####################################################################################################[OK]   key=value###################################################################################################def processWord(s):    global gObj    s = s.strip()    key,value = s.split("=",1)    key = key.strip(" \r\n")    value = value.strip(" \r\n")    gObj.addMember(key,value)####################################################################################################[OK]   getGroup("[Cache]") => "Cache"###################################################################################################def getGroup(str):    str = str.strip()    ret = re.match(r"\[(.+)\]$",str)    if ret != None:        return ret.group(1)    return None####################################################################################################[OK]   isGroup("[Cache]") => true###################################################################################################def isGroup(str):    str = str.strip()    ret = re.match(r"\[\w|\d]+\]$",str)    if ret != None:        return True    return False####################################################################################################[OK]   whether string is empty.###################################################################################################def isEmpty(str):    if len(str) <= 1:        return True    else:        return False####################################################################################################[OK]   parse the content of ini file,#       and generate the Node to gObjList.###################################################################################################def doParse(iniContent):    global gObj,gObjList    #getCin(hd)    varList = ""    fun_def_list = ""    lineList = []    m_group = ""        lineList = iniContent.split("\n")    isStart = True    for s in lineList:        s = s.strip()                       #   standared the string.        if isEmpty(s):                      #   ignore the space line.            continue        if re.match("#",s) != None:         #   ignore the conment line.            continue        if isGroup(s):                      #   is [Cache] field.            m_group = getGroup(s)            if isStart == True:                gObj.setGroup(m_group)                isStart = False            else:                gObjList.append(gObj)                gObj = CObject()                gObj.setGroup(m_group)        else:            processWord(s)    gObjList.append(gObj)####################################################################################################[OK]   read content from fname.###################################################################################################def readFile(fname):    with open(fname, 'r') as f:        return f.read()####################################################################################################[OK]   baseFilename("test.ini") => test###################################################################################################def baseFilename(fname):    name,ext = fname.rsplit(".")    return name####################################################################################################[OK]   genSetting.py test.ini ,  True#       check the user`s input args.###################################################################################################def checkArgs():    arg_len = len(sys.argv)    if arg_len != 2:        print "[Usage: genSetting.py test.ini]"        return False    return True####################################################################################################[OK]   checkFileFormat("test.ini") True###################################################################################################def checkFileFormat(fname):    ret = re.search(r'\w+\.ini$',fname)    if ret != None:        return True    return False####################################################################################################[OK]   Main Function.###################################################################################################def main():    global gObjList    if checkArgs() == False:        return    if checkFileFormat(sys.argv[1]) == False:        return    base_name = baseFilename(sys.argv[1])    iniContent = readFile(sys.argv[1])    doParse(iniContent)    m_varList = ""    m_defList = ""    m_impFunc = ""    m_getList = ""    m_initList = ""    for obj in gObjList:        m_varList = m_varList + obj.toVal_Def_List()        m_defList = m_defList + obj.toFunc_Def_List()        m_getList = m_getList + obj.toFunc_Get_List()        m_impFunc = m_impFunc + obj.toFunc_Set_List()        m_initList = m_initList + obj.toFunc_Init_List()    s1 = "void %s::loadFile(const string & fname){\n" % (gClassName)    s2 = "\tif (access(fname.c_str(),F_OK) != 0) \n\t{ \n\t\tprintf(\"file %s donot exist!\",fname.c_str());\n\t\treturn;\n\t}\n"    s3 = "\tIniFile _data;\n\t_data.open(fname);\n";    s4 = "}\n"    loadFunc = s1 + s2 + s3 + m_initList + m_impFunc + s4        saveHeadFile(m_defList,m_varList)    saveBodyFile(loadFunc,m_getList)main()


0 0
原创粉丝点击