使用Python產生源檔案的兩種方法,

來源:互聯網
上載者:User

使用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. ~ ~





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.