使用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 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请求

《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版]

《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码]

Python脚本获取Linux系统信息

在Ubuntu下用Python搭建桌面算法交易研究环境

Python 语言的发展简史

Python 的详细介绍:请点这里
Python 的下载地址:请点这里

本文永久更新链接地址:

本文永久更新链接地址:

相关内容

    暂无相关文章