利用Python的字符串處理模塊,開發者能夠編寫腳本用來生成那些格式同樣的C、C++、JAVA源程序、頭文件和測試文件,從而避免大量的反復工作。
本文概述兩種利用Python string類生成java源碼的方法。
1。String Template
Template是一個好東西,能夠將字符串的格式固定下來,反復利用。Template也能夠讓開發者能夠分別考慮字符串的格式和其內容了。無形中減輕了開發者的壓力。
Template屬於string中的一個類,有兩個重要的方法:substitute和safe_substitute。替換時使用substitute()。若未能提供模板所需的所有參數值時會發生異常。使用safe_substitute() 則會替換存在的字典值,保留未存在的替換符號。
要使用的話可用下面方式調用:
fromstringimportTemplate
Template有個特殊標示符$,它具有下面的規則:
(1)主要實現方式為$xxx,當中xxx是滿足python命名規則的字符串,即不能以數字開頭、不能為keyword等;
(2)假設$xxx須要和其它字符串接觸時,用{}將xxx包裹起來。
開發者通過編寫template文件,並通過Template方法創建模板、substitute方法替換字符串就可以快捷的生成所需的文件。編寫template文件時一定要注意“$”的使用,由於Python會將以“$”開頭的字符串理解成須要替換的變量。
2,replace
str.replace(old, new[, max])
Python replace() 方法把字符串中的 old(舊字符串) 替換成 new(新字符串)。假設指定第三個參數max,則替換不超過 max 次。
模板文件tenplate.java(自:基於模板的簡易代碼生成器Python源代碼)
/**
* 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:\\Project\\Python\\code_gen\\template.java'
path = 'D:\\Project\\Python\\code_gen\\'
testObjList = ['Basic_connect',\
'Sms',\
'Phonebook',\
]
for testObj in testObjList:
testObjVarName = testObj[0].lower() + testObj[1:]
filename = 'MBIM_Service_' + testObj +'_device.java'
author = 'AidanZhang'
version='V0.1'
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
tplFile = open(tplFilePath)
gFile = open(path+filename ,"w")
#method 1 with Template and substitute(safe_substitute)
lines=[]
tmp=Template(tplFile.read())
lines.append(tmp.substitute(
author = author,
now = now,
testObject = testObj,
testObjVarName = testObjVarName,
version = version))
gFile.writelines(lines)
'''
#Method 2, with replace
fileList = tplFile.readlines()
for fileLine in fileList:
line = fileLine.replace('${author}',author)\
.replace('${now}',now)\
.replace('${testObject}',testObj)\
.replace('${version}',version)\
.replace('${testObjVarName}',testObjVarName)
print line
gFile.writelines(line)
'''
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. ~ ~
