#!/usr/bin/env python#Filename: comment.pyimportos, sys, fileinput#-------------------------------------------------------------defusage():printu'''help: comment.py
[dirname]: Option, select a directory to operate
[filename]: Option, select a file to operate
Example: python comment.py /home/saylor/test'''#--------------------------------------------------------------defcommentFile(src, fileList):'''description: comment files
param src: Operate file name'''#if file exist?ifnotos.path.exists(src):print'Error: file - %s doesn\'t exist.'% srcreturnFalseifos.path.islink(src):print'Error: file - %s is just a link, will not handle it.'returnFalse
filetype=(os.path.splitext(src))[1]ifnotfiletypein['.c','.h']:returnFalsetry:ifnotos.access(src, os.W_OK):
os.chmod(src,0664)except:print'Error: you can not chang %s\'s mode.'% srctry:
inputf=open(src,'r')
outputfilename=src+'.tmp'outputf=open(outputfilename,'w')
beginLine=0
endLine=100000000isMatched=False#-----find the beginLine and endLine -------------------foreachlineinfileinput.input(src):ifeachline.find('/*')>=0:
beginLine=fileinput.lineno()ifeachline.find('Copyright 2002 Sun Microsystems, Inc. All rights reserved.')>=0:
isMatched=Trueifeachline.find('*/')>=0andisMatched:
endLine=fileinput.lineno()break#-----delete the content between beginLine and endLine-----printbeginLine, endLine
lineNo=1foreachlineininputf:iflineNo
outputf.write(eachline)eliflineNo>endLine:printeachline
outputf.write(eachline)
lineNo=lineNo+1inputf.close()
outputf.close()
os.rename(outputfilename, src)
fileList.append(src)except:print'Error: unexcept error.'inputf.close()
outputf.close()returnTrue#--------------------------------------------------------------defcommentDir(src, fileList):'''description:
comment files in src(dir)
param src:
operate files in src(dir)'''#if dir exist?ifnotos.path.exists(src):print'Error: dir - %s is not exist.'%s (src)returnFalse
filelists=os.listdir(src)foreachfileinfilelists:
eachfile=src+'/'+eachfileifos.path.isdir(eachfile):
commentDir(eachfile, fileList)elifos.path.isfile(eachfile):
commentFile(eachfile, fileList)returnTrue#--------------------------------------------------------------defmain():iflen(sys.argv)<2:
usage()
sys.exit(1)
src=sys.argv[1]ifos.path.isdir(src):
dire=os.path.abspath(src)
dirFlag=Trueelifos.path.isfile(src):
fl=os.path.abspath(src)
dirFlag=Falseelse:print'Error'fileList=[]ifdirFlag:
commentDir(dire, fileList)else:
commentFile(fl, fileList)iffileList:print'Successful handle file: ...'foreachfileinfileList:printeachfileprint'Done'returnTrue#--------------------------------------------------------------if__name__=='__main__':
main()