使用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命名规则的字符串,即不能以数字开头、不能为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:ProjectPythoncode_genMBIM_Service_Basic_connect_device.java over. ~ ~
generate D:ProjectPythoncode_genMBIM_Service_Sms_device.java over. ~ ~
generate D:ProjectPythoncode_genMBIM_Service_Phonebook_device.java over. ~ ~


原文地址:https://www.cnblogs.com/clnchanpin/p/6917958.html