# -*- coding: cp936 -*- #甄碼農python代碼 #日誌清除工具 import os import os.path import time import pprint import sys def clean(rootdir,logext,ageInDaysToClean=7): """ 清理rootdir目錄下超過ageInDaysToClean天未更新的擴展名爲logext的日誌文件 """ now = time.time() timeInSeconds = ageInDaysToClean*24*60*60 toclean = [] #找到過時日誌文件 for root,dirs,files in os.walk(rootdir,True,None,False) : #print root,dirs,files fs = [os.path.join(root,f) for f in files if os.path.splitext(f)[1] == logext and now - os.stat(os.path.join(root,f))[-2] > timeInSeconds] toclean.extend(fs) #刪除過時日誌文件 writetimes = map(lambda _: time.localtime(os.stat(_)[-2]),toclean) for f,t in zip(toclean,writetimes): print f,time.strftime('%Y-%m-%d %H:%M:%S',t) os.remove(f) #清空目錄 removedirs = [] for root,dirs,files in os.walk(rootdir): emptys = [os.path.join(root,dirname) for dirname in dirs if len(os.listdir(os.path.join(root,dirname))) == 0] removedirs.extend(emptys) pprint.pprint(removedirs) map(lambda _: os.rmdir(_),removedirs) if __name__ == '__main__': args = sys.argv[1:] if len(args) == 0 : print '必須指定日誌文件目錄' else : logdir = args[0] ext = '.log' if len(args)>0: ext = args[1] days = 7 if len(args)>1: days= int(args[2]) clean(logdir,ext,days) sys.exit(0)