[转]python代码⾃动⽣成的⽅法(代码⽣成器)
遇到的问题
⼯作中遇到这么⼀个事,需要写很多C++的底层数据库类,但这些类⼤同⼩异,⽆⾮是增删改查,如果⼈⼯来写代码,既费⼒⼜容易出错;⽽借⽤python的代码⾃动⽣成,可以轻松搞定;
(类⽐JAVA中的Hibernate⾃动⽣成的数据库底层操作代码)
下⾯介绍使⽤python字符串替换的⽅法;
Python字符串替换的⼏种⽅法
1. 字符串替换
将需要替换的内容使⽤格式化符替代,后续补上替换内容;
template = “hello %s , your website is %s ” % (“⼤CC”,”“)
print(template)
也可使⽤format函数完成:
template = “hello {0} , your website is {1} “.format(“⼤CC”,”“)
print(template)
注:该⽅法适⽤于变量少的单⾏字符串替换;
1. 字符串命名格式化符替换
使⽤命名格式化符,这样,对于多个相同变量的引⽤,在后续替换只⽤申明⼀次即可;
template = “hello %(name)s ,your name is %(name), your website is %(message)s” %{“name”:”⼤
CC”,”message”:”“}
print(template)
使⽤format函数的语法⽅式:
template = “hello {name} , your name is {name}, your website is {message} “.format(name=”⼤
CC”,message=”115”)
print(template)
注:适⽤相同变量较多的单⾏字符串替换;
3.模版⽅法替换
使⽤string中的Template⽅法;
from string import Template
tempTemplate = string.Template(“Hello message”)
print(tempTemplate.substitute(name=’⼤CC’,message=’‘))
有了模版⽅法后,就可以将模版保存到⽂件单独编辑,在⽣成的地⽅替换为需要的变量;
⽰例:代码⽣成
这个⽰例使⽤以上讲到的第三种⽅法;
建⽴⼀个模版⽂件,⾥⾯需要替换的内容使⽤${}变量替换;
plate
///
/// @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 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 = []
#模版⽂件
writelines方法的参数可以是template_file = open(r'plate','r')
tmpl = Template(ad())
#模版替换
lines.append(tmpl.substitute(
CLASSNAME = className,
TABLE_NAME = tableName,
TABLE_NAME_UPPER = tableName.upper(),
GENE_DATE = w().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++程序代码了;

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。