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

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


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

[Ku]
IP=192.168.64.10
Type=16
Position=0-c
AgentIP=192.168.3.77
ReportInterval=2

[Server]
IP=192.168.3.77
Port=7890

## 脚本如下( genCppIniParser.py )

#coding=utf-8
import os
import sys
import re
import shutil,string
from string import Template

gHearFile = "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}.h
Tile	  : 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
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值