首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java与python之编程之对照:一个简单的代码模板生成程序

2012-12-24 
java与python之编程之对比:一个简单的代码模板生成程序python部分的代码几乎是来息此文章:http://blog.sin

java与python之编程之对比:一个简单的代码模板生成程序
python部分的代码几乎是来息此文章:
http://blog.sina.com.cn/s/blog_4419b53f0100abzb.html
我小部分改进之后代码如下:

#-*- coding:utf-8 -*-# file :makeBasic.py#import osimport sysimport stringimport datetime# python 简单的脚本模板 def main():if os.path.isfile(sys.argv[1]):print '%s already exist!' % sys.argv[1]sys.exit()basic_template = open(sys.argv[1],'w') # create a file in write modetoday = datetime.date.today() # transform now to 'yyyy-mm-dd' s formatdate = today.strftime('%Y')+'-'+today.strftime('%m')+'-'+today.strftime('%d')filetypes = string.split(sys.argv[1],'.') # 判断文件类型length = len(filetypes)filetype = filetypes[length -1]print 'file type is :'+filetypeif filetype == 'py':print 'use python mode'basic_template.writelines('#-*- coding:utf-8 -*-')basic_template.write('\n')basic_template.writelines('# file :'+sys.argv[1])basic_template.write('\n')basic_template.write('# date :'+date)basic_template.write('\n') basic_template.write('##----------------------------------------------------')basic_template.write('\n')print 'template create successfully' else:print 'not support other file time currently'basic_template.close() # 关闭文件if __name__ == '__main__':main()


使用方法如下:
package me.banxi.io;import java.io.File;import java.io.FileNotFoundException;import java.io.PrintWriter;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Scanner;public class MakeCode{public static void usage(){StringBuilder builder = new StringBuilder(1024);builder.append(" Usage:\n");builder.append(" unix-like: $ java MakeCode yourSourceFileName \n");builder.append(" example: $ java MakeCode HelloWorld.java");builder.append(" -------------------the end ------------------------------");System.out.println(builder.toString());}//:usagepublic static void notSupport(String fileName){String []strs = fileName.split(".");if(strs.length < 1) {System.out.println("you have not give a file .suffix! file type of "+fileName+"are not support now!");}else {System.out.println("file type of "+strs[strs.length-1]+"are not support now!");}}//:notSupportpublic static boolean cancelCreate( String name ){System.out.println("file with name of "+name+"is already exists!\n");System.out.println("do you want to build a new file?(y/n)");Scanner scanner = new Scanner(System.in);String yesOrNo = scanner.next();if(yesOrNo.equalsIgnoreCase("y")) {return false;}return true;}//:isContinueprivate static void createTemplate(File file) {PrintWriter writer = null;try {writer = new PrintWriter(file);StringBuilder builder = new StringBuilder(256);builder.append("import java.io.*;\n");builder.append("import java.util.*;\n");builder.append("/**\n");builder.append(" * @author yourName \n");builder.append(" * @date "+(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));builder.append("\n */\n");builder.append("public class "+file.getName());builder.append("{\n");builder.append("\n");builder.append("}\n");writer.write(builder.toString());writer.flush();} catch (FileNotFoundException e) {System.out.println("no such file:"+file.getAbsolutePath());e.printStackTrace();}finally {if(writer != null) {writer.close();}}}// :createTemplatepublic static void main(String ... args){if(args.length < 1){usage();System.exit(1);}//String fileName = args[args.length -1];if(fileName.endsWith(".java")){File file = new File(fileName);if(file.exists()){if(cancelCreate(file.getName())){System.exit(1);}}createTemplate(file);System.out.println("create java source template successfully!");System.out.println("file's full name was:"+file.getAbsolutePath());}else{notSupport(fileName);System.exit(1);}}//}//:end MakeCode/** * 运行结果:file with name of MyFileReader.javais already exists!do you want to build a new file?(y/n)ycreate java source template successfully!file's full name was:/home/banxi1988/work/tomcat7/JavaIo/MyFileReader.java生成模板内容:import java.io.*;import java.util.*;** * @author yourName * @date 2011-10-10 23:17:40 *public class MyFileReader.java{} */


python版的我修改之后如下:
主要修改了,如果没有传递参数,提示用法.
时期精确到时分秒.
如果已经有文件了提示是否创建新的:
#-*- coding:utf-8 -*-# file :makeBasic.py#import osimport sysimport stringfrom datetime import datetime# python 简单的脚本模板 def usage():usages = """ Usage: unix-like usage:$ python makeBasic myfile.py example :       $ python makeBasic helloworld.py"""print usagesdef main():if len(sys.argv) < 2:usage()sys.exit()if os.path.isfile(sys.argv[1]):print '%s already exist!' % sys.argv[1]yesOrNo = raw_input ('do you still want to create a new file?(y/n)')if(yesOrNo.strip().lower() == 'n'):sys.exit()basic_template = open(sys.argv[1],'w') # create a file in write modedate = datetime.now().strftime('%Y-%m-%d %H:%M:%S')filetypes = string.split(sys.argv[1],'.') # 判断将创建的文件是什么类型然后分别处理length = len(filetypes)filetype = filetypes[length -1]print 'file type is :'+filetypeif filetype == 'py':print 'use python mode'basic_template.writelines('#-*- coding:utf-8 -*-')basic_template.write('\n')basic_template.writelines('# file :'+sys.argv[1])basic_template.write('\n')basic_template.write('# date :'+date)basic_template.write('\n')basic_template.write('##----------------------------------------------------')basic_template.write('\n')print 'template create successfully' else:print 'not support other file time currently'basic_template.close() # 关闭文件if __name__ == '__main__':main()

热点排行