Python:在Linux下创建一个脚本并且自动修改权限,可以选择路径。批量生成脚本 。

最近忙着写一些脚本,但是从创建到改变脚本的权限,使其能够执行,并且想在某些目录下批量创建脚本,执行起来比较麻烦,所以用Python编写了一个小脚本来一部完成所有的内容。执行后,就可以直接进入脚本进行编辑了。如果批量创建脚本,不会进入脚本,但是会告诉用户哪些脚本已经存在,哪些已经成功创建了。所生成的脚本有:python, bash, perl, php, javascript, html/htm。

有一个问题,getopt中的option如果是写在arguments之后,则会被归类到argument之中,这和其他unix命令不符。所有需要添加一个对args的确认,例如:

#check if arguments are legal
if args:
for arg in args:
if re.match("^\-\w", arg):
usage()
else:
#if no arguments
print "Please Enter Script Name!"
sys.exit(2)

下面是代码全文:

  1 #!/usr/bin/env python
  2 #_*_coding:utf-8_*_
  3 """
  4 this script is for creating the script more efficiently.
  5 version: 6.0 """
  6 import os
  7 import sys
  8 import re
  9 import time
 10 
 11 class SCRIPTS(object):
 12     "create the script arcording to extention name"
 13     def __init__(self, script_names, dir_path='.', title=''):
 14         "script_names is required"
 15         self.scriptNames=script_names
 16         self.dirPath=dir_path
 17         self.title=title
 18 
 19     def create(self):
 20         "create the script(s)"
 21         # if there is only one script and exists!
 22         if isinstance(self.scriptNames, list) and len(self.scriptNames)==1 or \
 23             isinstance(self.scriptNames, str):
 24             scriptpath=os.path.join(self.dirPath, "".join(self.scriptNames)) # build a full path
 25             if os.path.isfile(scriptpath): # if the script exists!
 26                 self.vim(scriptpath)
 27                 return True
 28             else: 
 29                 if self._create_single_script(scriptpath):
 30                     self.vim(scriptpath)
 31                 return True
 32 
 33         elif isinstance(self.scriptNames, list):
 34             for scriptname in self.scriptNames:
 35                 self._create_single_script(os.path.join(scriptname, self.dirPath)) # create one by one
 36             return True
 37 
 38     def _create_single_script(self, scriptpath):
 39         "create a single script ; scriptpath is supposed to be a str"
 40         createtime=time.strftime("%Y-%m-%d", time.localtime()) #get local time
 41         ext=scriptpath.rpartition(".")[2] # file extent
 42 
 43         # verify scriptpath
 44         if os.path.isfile(scriptpath):
 45             print "%s: exits !" % os.path.basename(scriptpath)
 46             return False # not able to create the script file
 47         elif not ext:
 48             print "%s: need extention !" % os.path.basename(scriptpath)
 49             return False # not able to create the script file
 50         elif not re.search('\.(?:php|sh|pl|js|py|chm|html|[cCh]|cpp|java)$', scriptpath):
 51             print "%s: extention should be sh,py,php,html,js,chm,h,java,c,cpp or C" % \
 52                 os.path.basename(scriptpath)
 53             return False # not able to create the script
 54 
 55         # create the script and put infors into it
 56         if not self.title: # usually not given
 57             self.title=os.path.basename(scriptpath)
 58         #    title=os.path.basename(scriptpath).rpartition(".")[0]
 59 
 60         htmlFormat="<!DOCTYPE HTML PUBLIC\"-//W3C/DTD HTML4.01//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n" \
 61             "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<meta name=\"Keywords\"" \
 62             "content=\"\">\n<meta name=\"Description\" content=\"%s\">\n<meta name=\"Author\" content=\"NathanHuang\">\n" \
 63             "<title>%s</title>\n<script type=\"text/javascript\" src=></script>\n<script type=\"text/javascript\">\n</script>\n"\
 64             "</head><body>\n\n</body></html>" % (createtime, self.title)
 65 
 66         bashFormat="#!/usr/bin/env bash\n#\n# SCRIPT: %s\n# AUTHOR: Nathan Huang\n# DATE: %s\n# REV:1.0\n# PLATFORM:\n# PURPOSE:\n#\n"\
 67             "# REV LIST: \n#\nPATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:~/.local/bin:~/bin\nexport PATH\n"\
 68                 % (self.title, createtime)
 69         try:
 70             # write lines to file
 71             filename=os.path.basename(scriptpath).rpartition(".")[0]    
 72             if ext=='py':
 73                 f=open(scriptpath, "w") # open the script
 74                 f.writelines("#!/usr/bin/env python\n\"File: %s -- \"\n" % filename)
 75                 os.chmod(scriptpath, 0755) #chmod script
 76             elif ext=='php':
 77                 f=open(scriptpath, "w") # open the script
 78                 f.writelines("<?php\n/*\n *\n *\n */\n?>")
 79             elif ext=='sh':
 80                 f=open(scriptpath, "w") # open the script
 81                 f.writelines(bashFormat)
 82                 os.chmod(scriptpath, 0755) #chmod script
 83             elif ext in ('c', 'C', 'cpp'):
 84                 f=open(scriptpath, "w") # open the script
 85                 f.writelines("/* File: %s\n *------------------\n *\n*/\n" % filename)
 86             elif ext=='pl':
 87                 f=open(scriptpath, "w") # open the script
 88                 f.writelines("#!/usr/bin/env perl\nuse strict;\nuse warnings;\n")
 89                 os.chmod(scriptpath, 0755) #chmod script
 90             elif ext=='java':
 91                 f=open(scriptpath, "w") # open the script
 92                 f.writelines("/**\n *\n *@version 1.00 \n *@author Nathan Huang \n */\n\npublic class %s {\n}" % filename)
 93             elif ext=='js':
 94                 f=open(scriptpath, "w") # open the script
 95                 f.writelines("/*\n *Author: Nathan Huang\n *Script: %s*/" % filename)
 96             elif ext in ('html', 'chm'):
 97                 f=open(scriptpath, "w") # open the script
 98                 f.writelines(htmlFormat)
 99             f.close() # close the script 
100 
101         except IOError, err:
102             print str(err)    
103             return False # not able to create the script
104 
105         return True
106 
107     def vim(self, scriptpath):
108         if scriptpath:
109             os.system("vim %s" % scriptpath)
110             return True
111         else:
112             return False
113 
114 
115 
116 def _usage():
117     print "usage: ", os.path.basename(sys.argv[0]), " [-h] [-o] [-t] filename..."
118     print "-h: help"
119     print "-o path"
120     print "-t title"
121     sys.exit(0)
122 
123 def main():
124     import getopt
125     if not sys.argv[1:]:
126         _usage()
127     try:
128         opts, args=getopt.getopt(sys.argv[1:], 'ho:t:')
129     except getopt.getoptError:
130         sys.stdout=sys.stderr
131         _usage()
132 
133     #check if args have legal contents
134     if args:
135         for arg in args:
136             if re.match("^\-\w", arg):
137                 _usage() # if one match was found, program will exit. so we can not find the double useage ouput.
138 
139     # parsing the options,all opts are supposed before the args
140     title=''
141     dir_path='./'
142     for o, a in opts:
143         if o=='-h':
144             _usage()
145         if o=='-o':
146             dir_path=a
147         if o=='-t':
148             title=a
149     # start ...
150     kk=SCRIPTS(args, dir_path, title)
151     kk.create()
152 
153 if __name__ == '__main__':
154     main()
posted @ 2012-03-01 14:41  CCJPP  阅读(828)  评论(0)    收藏  举报