python小脚本-clean log
#!/usr/bin/python#ecoding=utf-8'''清理磁盘,当空间小于某个值时执行定时任务'''import os,timeproportion=90#磁盘空间比例,当大于此值是清理磁盘path='/usr/local/yhxxbak/'#处理磁盘路径endwith='.tar.gz'#处理日志文件的后缀use=os.popen(r'df -h|grep /dev/sda2').read().split()[-2][:-1]#磁盘使用量log=file(os.path.join(path,'clean.log'),'a')#记录日志log.write(time.ctime(time.time())+' Timing clean task is executed'+os.linesep)if int(use)>proportion: log.write(' Space is not enough,system use %d%' %int(use)) log.write(os.linesep)else: log.write(' Space is enough') log.write(os.linesep)while int(use)>proportion: filemap={} for f in [x for x in os.listdir(path) if x.endswith(endwith)]:#处理以.tar.gz结尾的文件 tmp=os.path.join(path,f) filemap[os.stat(tmp).st_mtime]=tmp if filemap:#有文件时处理 to_del=filemap[min(filemap.keys())] log.write(' File:'+to_del+" create time:"+time.ctime(os.stat(to_del).st_mtime)+" is deleted!"+os.linesep) os.remove(to_del) use=os.popen(r'df -h|grep /dev/sda2').read().split()[-2][:-1] if not filemap:#没有文件时,打印换行的日志 log.write(' No file to clean'+os.linesep) break;log.close()?