python 自動生成C++代碼 (代碼生成器)


python 代碼自動生成的方法 (代碼生成器)

遇到的問題

工作中遇到這么一個事,需要寫很多C++的底層數據庫類,但這些類大同小異,無非是增刪改查,如果人工來寫代碼,既費力又容易出錯;而借用python的代碼自動生成,可以輕松搞定;
(類比JAVA中的Hibernate自動生成的數據庫底層操作代碼)
下面介紹使用python字符串替換的方法;

Python字符串替換的幾種方法

1. 字符串替換
將需要替換的內容使用格式化符替代,后續補上替換內容;

template = "hello %s , your website  is %s " % ("大CC","http://blog.me115.com")
print(template)

也可使用format函數完成:

template = "hello {0} , your website  is {1} ".format("大CC","http://blog.me115.com")
print(template)

注:該方法適用於變量少的單行字符串替換;

2. 字符串命名格式化符替換
使用命名格式化符,這樣,對於多個相同變量的引用,在后續替換只用申明一次即可;

template = "hello %(name)s ,your name is %(name), your website  is %(message)s" %{"name":"大CC","message":"http://blog.me115.com"}
print(template)

使用format函數的語法方式:

template = "hello {name} , your name is {name}, your website  is {message} ".format(name="大CC",message="http://blog.me115.com")
print(template)

注:適用相同變量較多的單行字符串替換;

3.模版方法替換
使用string中的Template方法;

from string import Template
tempTemplate = string.Template("Hello $name ,your website is $message")
print(tempTemplate.substitute(name='大CC',message='http://blog.me115.com'))

有了模版方法后,就可以將模版保存到文件單獨編輯,在生成的地方替換為需要的變量;

示例:代碼生成

這個示例使用以上講到的第三種方法;
建立一個模版文件,里面需要替換的內容使用${}變量替換;
dao_cpp.template

///
/// @class ${CLASSNAME}
/// @brief Redis底層接口類 操作${TABLE_NAME}表
/// TABLE ${TABLE_NAME_UPPER}
/// @author dao_cpp_generator.py
/// @generate date: ${GENE_DATE}
/// [注:本文件為自動生成,不需要人為編輯,若有修改,請通過配置py腳本來重新生成.]

#include "${CLASSNAME}.h"
#include "include/${TABLE_NAME}_t.h"
#include "RedisManager.h"
#include "common/LogMacros.h"
#include "common/StringUtility/OtherStringFunc.h"
#include "common/DateTime.h"

namespace redisdao{

#define PRIMARY_KEY "${PRIMER_KEY}"
const string ${CLASSNAME}::TABLE_NAME = "${TABLE_NAME}";
const string ${CLASSNAME}::TABLE_ID = "${TABLE_ID}"; //在數據庫中的表的唯一性標識符
const string ${CLASSNAME}::KEY_SEPARETER = "${KEY_SEPARETER}";

${CLASSNAME}::${CLASSNAME}(void)
{
    if ( 0 == m_reHandler.EnsureConnect())
        m_bRedisConnected = true;
    else
        m_bRedisConnected = false;
}

${CLASSNAME}::~${CLASSNAME}(void)
{
}

int ${CLASSNAME}::InsertRecord(const string& strVal)
...

python代碼生成程序:
cpp_generator.py

#! /usr/bin/env python
#coding=utf-8
#Redis底層操作類CPP文件生成程序(*RedisDao.cpp)
#author me115@126.com 2014-7-22
import os,sys,re,traceback
from datetime import datetime
from string import Template

class DaoCppGenerator:

    def generate(self):
        tableName = 'students'
        className = '%sRedisDao' %  tableName.capitalize()
        filePath = r'include/%s.cpp' % className
        class_file = open(filePath,'w')

        lines = []

        #模版文件
        template_file = open(r'dao_cpp.template','r')
        tmpl = Template(template_file.read())

        #模版替換
        lines.append(tmpl.substitute(
                    CLASSNAME = className,
                    TABLE_NAME = tableName,
                    TABLE_NAME_UPPER = tableName.upper(), 
                    GENE_DATE = datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                    TABLE_ID = '115',
                    EXPIRE_DATE = '06JUN14'))

        # 0.將生成的代碼寫入文件
        class_file.writelines(lines)
        class_file.close()

        print 'generate %s over. ~ ~' % filePath

有了這個程序,再配合一堆XML配置文件,就可以輕松生成各種C++程序代碼了;

Posted by: 大CC | 25JUL,2014
博客:blog.me115.com [訂閱]
微博:新浪微博


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM