使用Python產生源檔案的兩種方法,
利用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命名規則的字串,即不能以數字開頭、不能為關鍵字等;
(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 osimport datetimefrom string import TemplatetplFilePath = '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. ~ ~