您的位置:首页 > 运维架构 > Linux

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

2012-03-01 14:41 1086 查看
最近忙着写一些脚本,但是从创建到改变脚本的权限,使其能够执行,并且想在某些目录下批量创建脚本,执行起来比较麻烦,所以用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)


下面是代码全文:

#!/usr/bin/env python
#_*_coding:utf-8_*_
"""
this script is for creating the script more efficiently.
version: 6.0 """
import os
import sys
import re
import time

class SCRIPTS(object):
"create the script arcording to extention name"
def __init__(self, script_names, dir_path='.', title=''):
"script_names is required"
self.scriptNames=script_names
self.dirPath=dir_path
self.title=title

def create(self):
"create the script(s)"
# if there is only one script and exists!
if isinstance(self.scriptNames, list) and len(self.scriptNames)==1 or \
isinstance(self.scriptNames, str):
scriptpath=os.path.join(self.dirPath, "".join(self.scriptNames)) # build a full path
if os.path.isfile(scriptpath): # if the script exists!
self.vim(scriptpath)
return True
else:
if self._create_single_script(scriptpath):
self.vim(scriptpath)
return True

elif isinstance(self.scriptNames, list):
for scriptname in self.scriptNames:
self._create_single_script(os.path.join(scriptname, self.dirPath)) # create one by one
return True

def _create_single_script(self, scriptpath):
"create a single script ; scriptpath is supposed to be a str"
createtime=time.strftime("%Y-%m-%d", time.localtime()) #get local time
ext=scriptpath.rpartition(".")[2] # file extent

# verify scriptpath
if os.path.isfile(scriptpath):
print "%s: exits !" % os.path.basename(scriptpath)
return False # not able to create the script file
elif not ext:
print "%s: need extention !" % os.path.basename(scriptpath)
return False # not able to create the script file
elif not re.search('\.(?:php|sh|pl|js|py|chm|html|[cCh]|cpp|java)$', scriptpath):
print "%s: extention should be sh,py,php,html,js,chm,h,java,c,cpp or C" % \
os.path.basename(scriptpath)
return False # not able to create the script

# create the script and put infors into it
if not self.title: # usually not given
self.title=os.path.basename(scriptpath)
#    title=os.path.basename(scriptpath).rpartition(".")[0]

htmlFormat="<!DOCTYPE HTML PUBLIC\"-//W3C/DTD HTML4.01//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n" \
"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<meta name=\"Keywords\"" \
"content=\"\">\n<meta name=\"Description\" content=\"%s\">\n<meta name=\"Author\" content=\"NathanHuang\">\n" \
"<title>%s</title>\n<script type=\"text/javascript\" src=></script>\n<script type=\"text/javascript\">\n</script>\n"\
"</head><body>\n\n</body></html>" % (createtime, self.title)

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"\
"# REV LIST: \n#\nPATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:~/.local/bin:~/bin\nexport PATH\n"\
% (self.title, createtime)
try:
# write lines to file
filename=os.path.basename(scriptpath).rpartition(".")[0]
if ext=='py':
f=open(scriptpath, "w") # open the script
f.writelines("#!/usr/bin/env python\n\"File: %s -- \"\n" % filename)
os.chmod(scriptpath, 0755) #chmod script
elif ext=='php':
f=open(scriptpath, "w") # open the script
f.writelines("<?php\n/*\n *\n *\n */\n?>")
elif ext=='sh':
f=open(scriptpath, "w") # open the script
f.writelines(bashFormat)
os.chmod(scriptpath, 0755) #chmod script
elif ext in ('c', 'C', 'cpp'):
f=open(scriptpath, "w") # open the script
f.writelines("/* File: %s\n *------------------\n *\n*/\n" % filename)
elif ext=='pl':
f=open(scriptpath, "w") # open the script
f.writelines("#!/usr/bin/env perl\nuse strict;\nuse warnings;\n")
os.chmod(scriptpath, 0755) #chmod script
elif ext=='java':
f=open(scriptpath, "w") # open the script
f.writelines("/**\n *\n *@version 1.00 \n *@author Nathan Huang \n */\n\npublic class %s {\n}" % filename)
elif ext=='js':
f=open(scriptpath, "w") # open the script
f.writelines("/*\n *Author: Nathan Huang\n *Script: %s*/" % filename)
elif ext in ('html', 'chm'):
f=open(scriptpath, "w") # open the script
f.writelines(htmlFormat)
f.close() # close the script

except IOError, err:
print str(err)
return False # not able to create the script

return True

def vim(self, scriptpath):
if scriptpath:
os.system("vim %s" % scriptpath)
return True
else:
return False

def _usage():
print "usage: ", os.path.basename(sys.argv[0]), " [-h] [-o] [-t] filename..."
print "-h: help"
print "-o path"
print "-t title"
sys.exit(0)

def main():
import getopt
if not sys.argv[1:]:
_usage()
try:
opts, args=getopt.getopt(sys.argv[1:], 'ho:t:')
except getopt.getoptError:
sys.stdout=sys.stderr
_usage()

#check if args have legal contents
if args:
for arg in args:
if re.match("^\-\w", arg):
_usage() # if one match was found, program will exit. so we can not find the double useage ouput.

# parsing the options,all opts are supposed before the args
title=''
dir_path='./'
for o, a in opts:
if o=='-h':
_usage()
if o=='-o':
dir_path=a
if o=='-t':
title=a
# start ...
kk=SCRIPTS(args, dir_path, title)
kk.create()

if __name__ == '__main__':
main()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐