歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 使用Python生成源文件的兩種方法

使用Python生成源文件的兩種方法

日期:2017/3/1 9:38:36   编辑:Linux編程

利用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源碼 http://www.linuxidc.com/Linux/2014-10/108262.htm)

/**
* 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. ~ ~

Python向PHP發起GET與POST請求 http://www.linuxidc.com/Linux/2014-10/107903.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved