Use Python to generate source files,

Source: Internet
Author: User

Use Python to generate source files,

Using the Python string processing module, developers can write scripts to generate C, C ++, JAVA source programs, header files, and test files in the same format, so as to avoid a lot of repetitive work. This article describes two methods to generate java source code using the Python string class.

1, String Template

Template is a good thing. It can fix the string format and reuse it. Template also allows developers to consider the string format and content separately, which virtually reduces the pressure on developers. Template is a class in string and has two important methods: substitute and safe_substitute. Use substitute () for replacement. If you fail to provide all the parameter values required by the template, an exception occurs. When safe_substitute () is used, the existing dictionary value is replaced and the existing replacement symbols are retained. You can use the following methods to call a service:

fromstringimportTemplate

A Template has a special identifier $, which has the following rules:

(1) The main implementation method is $ xxx, where xxx is a string that meets the python naming rules, that is, it cannot start with a number or be a keyword;

(2) If $ xxx needs to be in contact with other strings, use {} To wrap xxx;

Developers can quickly generate the required files by writing a template file, creating a Template using the template method, and replacing the string using the substitute method. Note the usage of "$" when writing a template file, because Python will understand the string starting with "$" as the variable to be replaced.

2, replace

    str.replace(old, new[, max])

The Python replace () method replaces the old (old string) in the string with new (new String). If the third parameter max is specified, the replacement cannot exceed max.

Template File tenplate. java (SELF: simple template-based code generator Python source code)

/**    * 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 code

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)


Running result

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





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.