Two ways to generate source files using Python

Source: Internet
Author: User
Tags assert

Using Python's string processing module, developers can write scripts to generate the same C, C + +, Java source programs, header files, and test files in the same format, avoiding a lot of repetitive work.

This article outlines two methods for generating Java source code using the Python string class.

1. String Template

The template is a good thing to be able to pin down the format of a string and use it repeatedly. Template also enables developers to consider the format and content of the string separately. Virtually relieves the developer of the pressure.

The template belongs to a class in string and has two important methods: substitute and Safe_substitute. Use substitute () when replacing. An exception occurs if all the parameters required by the template are not available. Using Safe_substitute () replaces the existing dictionary value, preserving the non-existent substitution symbol.

To use it, it can be called in the following way:

fromstringimportTemplate

The template has a special identifier of $, which has the following rules:

(1) The main implementation mode is $xxx, in which xxx is a string that satisfies the naming rules of Python, that is, it cannot start with a number, cannot be keyword, etc.

(2) Assuming that $xxx needs to contact other strings, use {} to wrap xxx together.

The developer can quickly generate the required files by writing a template file and creating templates using the templated method, substitute method substitution strings. Be sure to note the use of "$" when writing a template file, because Python will interpret a string that begins with "$" as a variable that needs to be replaced.

2,replace

    Str.replace (old, new[, Max])

The Python replace () method replaces the old (older string) in the string with the new string. Assuming that the third parameter max is specified, the substitution does not exceed Max times.

template file Tenplate.java (from: template-based simple 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} */Pub Lic class Ibatis${testobject}daotester extends Annotatedautowiresofatestcase {@Override public string[] Getco Nfigurationlocations () {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_ ' + test OBJ + ' _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 = Autho                 R, 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} ', TestO Bjvarname) Print line gfile.writelines (line) "Tplfile.close () gfile.close () print ' Generate% S over. ~ ~ '% (path+filename)


Execution results

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


Two ways to generate source files using Python

Related Article

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.