- 论坛徽章:
- 0
|
我也来现下丑,看到前面那些精短的回答,我汗颜
下面的代码功能是:
可以注释指定目录及其子目录中所有中的‘ca::ctrlaltdel:/sbin/shutdown -r -t 4 now’
或指定文件中的‘ca::ctrlaltdel:/sbin/shutdown -r -t 4 now’
稍加修改,可以进行批量文件处理、处理指定目录or文件。。。。- #!/usr/bin/env python
- #Filename: comment.py
- import os, sys
- #-------------------------------------------------------------
- def usage():
- print u'''
- help: comment.py <filename | dirname>
- [dirname]: Option, select a directory to operate
- [filename]: Option, select a file to operate
- Example: python comment.py /home/saylor/test
- '''
- #--------------------------------------------------------------
- def commentFile(src, fileList):
- '''
- description: comment files
- param src: Operate file name
- '''
- #if file exist?
- if not os.path.exists(src):
- print 'Error: file - %s doesn\'t exist.'% src
- return False
- if os.path.islink(src):
- print 'Error: file - %s is just a link, will not handle it.'
- return False
- filetype = (os.path.splitext(src))[1]
- if not filetype in ['.c','.h']:
- return False
- try:
- if not os.access(src, os.W_OK):
- os.chmod(src, 0664)
- except:
- print 'Error: you can not chang %s\'s mode.'% src
- try:
- inputf = open(src, 'r')
- outputfilename = src + '.tmp'
- outputf = open(outputfilename, 'w')
- str = 'ca::ctrlaltdel:/sbin/shutdown -r -t 4 now'
- for eachline in inputf:
- if eachline.find('::ctrlaltdel:/sbin/shutdown -r -t 4 now') > 0:
- print 'run here'
- eachline = eachline.replace('ca::ctrlaltdel:/sbin/shutdown -r -t 4 now','#ca::ctrlaltdel:/sbin/shutdown -r -t 4 now')
- outputf.write(eachline)
- inputf.close()
- outputf.close()
- os.rename(outputfilename, src)
- fileList.append(src)
- except:
- print 'Error: unexcept error.'
- inputf.close()
- outputf.close()
- return True
- #--------------------------------------------------------------
- def commentDir(src, fileList):
- '''
- description:
- comment files in src(dir)
- param src:
- operate files in src(dir)
- '''
- #if dir exist?
- if not os.path.exists(src):
- print 'Error: dir - %s is not exist.'%s (src)
- return False
- filelists = os.listdir(src)
- for eachfile in filelists:
- eachfile = src + '/' +eachfile
- if os.path.isdir(eachfile):
- commentDir(eachfile, fileList)
- elif os.path.isfile(eachfile):
- commentFile(eachfile, fileList)
- return True
- #--------------------------------------------------------------
- def main():
- if len(sys.argv) < 2:
- usage()
- sys.exit(1)
- src = sys.argv[1]
- if os.path.isdir(src):
- dire = os.path.abspath(src)
- dirFlag = True
- elif os.path.isfile(src):
- fl = os.path.abspath(src)
- dirFlag = False
- else:
- print 'Error'
- fileList = []
- if dirFlag:
- commentDir(dire, fileList)
- else:
- commentFile(fl, fileList)
- if fileList:
- print 'Successful handle file: ...'
- for eachfile in fileList:
- print eachfile
- print 'Done'
- return True
- #--------------------------------------------------------------
- if __name__ == '__main__':
- main()
复制代码 |
|