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 formats of C, C + +, Java source programs, header files, and test files, thus avoiding a lot of duplication of effort. This article outlines two methods for generating Java source code using the Python string class.

1,string Template

The template is a good thing that can be used to fix the format of a string and reuse it. Template can also allow developers to consider the format of the string and its contents, virtually reducing the pressure on developers. The template belongs to a class in string and has two important methods: substitute and Safe_substitute. Replace with substitute (), an exception occurs if you fail to provide all of the parameter values required by the template. Using Safe_substitute () replaces the existing dictionary value, preserving the non-existent substitution symbol. To use it, you can call it in the following ways:

fromstringimportTemplate

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

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

(2) If $xxx need to contact with other strings, use {} to wrap the XXX together;

Developers can quickly generate the required files by writing a template file and creating templates by 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 one, and if you specify the third parameter max, the replacement does not exceed Max times.

template file Tenplate.java (from: template-based simple code generator python source )

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


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