How to use Pyhton to generate source file of 2 ways

利用Python的字符串处理模块,开发人员可以编写脚本用来生成那些格式相同的C、C++、JAVA源程序、头文件和测试文件,从而避免大量的重复工作。本文概述两种利用Python string类生成java源代码的方法。

String Template

Template是一个好东西,可以将字符串的格式固定下来,重复利用。Template也可以让开发人员可以分别考虑字符串的格式和其内容了,无形中减轻了开发人员的压力。Template属于string中的一个类,有两个重要的方法:substitute和safe_substitute。替换时使用substitute(),若未能提供模板所需的全部参数值时会发生异常。使用safe_substitute() 则会替换存在的字典值,保留未存在的替换符号。要使用的话可用以下方式调用:

from string import Template

Template有个特殊标示符$,它具有以下的规则:

(1)主要实现方式为$xxx,其中xxx是满足python命名规则的字符串,即不能以数字开头、不能为关键字等;

(2)如果$xxx需要和其他字符串接触时,用{}将xxx包裹起来;

开发人员通过编写template文件,并通过Template方法创建模板、substitute方法替换字符串即可快捷的生成所需的文件。编写template文件时一定要注意“$”的使用,因为Python会将以“$”开头的字符串理解成需要替换的变量。

replace

str.replace(old,new[,max])

Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

模板文件tenplate.java

/**
* created since ${now}
*/
package com.alipay.mspcore.common.dal.ibatis;
import java.util.Date;
import junit.framework.Assert;
import com.alipay.mspcore.common.dal.daointerface.${testObject}DAO;
import com.alipay.mspcore.common.dal.dataobject.${testObject};
import com.alipay.sofa.runtime.test.AnnotatedAutowireSofaTestCase;
import com.iwallet.biz.common.util.money.Money;
/**
* @author ${author}
* @version ${version}: MBIM_Service${testObject}_Device.java, ${now} ${author}
*/
public class Ibatis${testObject}DAOTester extends AnnotatedAutowireSofaTestCase {
    @Override
    public String[] getConfigurationLocations() {
        return new String[] { "META-INF/spring/common-dal-db.xml",
            "META-INF/spring/mobilespcore-common-dal-dao.xml",
            "META-INF/spring/common-dal.xml" };
    }
    @Override
    public String[] getResourceFilterNames() {
        return new String[] { "META-INF/spring/common-dal-db.xml" };
    }
    @Override
    public String[] getWebServiceConfigurationLocations() {
        return new String[] {};
    }
    private ${testObject}DAO get${testObject}DAO() {
        ${testObject}DAO dao = (${testObject}DAO) this.getBean("${testObjVarName}DAO", ${testObject}DAO.class, null);
        return dao;
    }
    public void test${testObject}DAO() {
        ${testObject}DAO configDAO = get${testObject}DAO();
        Assert.assertNotNull(configDAO);
    }
    public void test() {
        ${testObject}DO ${testObjVarName}DO = new ${testObject}DO();
        ${testObjVarName}DO.setGmtCreate(new Date());
        ${testObjVarName}DO.setGmtModified(new Date());
        ${testObjVarName}DO.setId(10000);
        ${testObject}DAO ${testObjVarName}DAO = get${testObject}DAO();
        long result = ${testObjVarName}DAO.insert(${testObjVarName}DO);
        Assert.assertTrue(result > 0);
    }
}

Python代码

import os
import datetime
from string import Template

tplFilePath="D:\\template.java"
path="D:\\code_gen"
testObjectList=['Basic_connect','Sms','Phonebook']

for testObj in testObjectList:
    testObjVarName=testObj[0].lower() + testObj[1:]
    filename="MBIM_Service_" + testObj + '_device.java'
author='Aye'
version='0.1'
now=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

tplFile=open(tplFilePath)
gFile=open(pathfilename,'w')

lines=[]
tmp=Template(tplFile.read())
lines.append(tmp.substitute(author=author,now=now,version=version))
gFile.weitelines(lines)

tplFile.close()
gFile.close()
print 'generate %s over.~~' % (path+filename)

运行结果

generate D:\Project\Python\code_gen\MBIM_Service_Basic_connect_device.java over. ~ ~
generate D:\Project\Python\code_gen\MBIM_Service_Sms_device.java over. ~ ~
generate D:\Project\Python\code_gen\MBIM_Service_Phonebook_device.java over. ~ ~