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 [订阅]
微博:新浪微博
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述