脚本1:
这两天用python写了一个删除指定目录下过期时间的脚本。也可能是我初学python,对python还不够熟习,总觉得这个脚本用shell写应该更简单也更容易些。
就功能上来说,该脚本已经实现了我想要的效果,不过该脚本还不够通用性,还有更多可以完善的地方。目前该脚本在python2.4下运行良好。同时,我在脚本中加入了对python版本的判断,理论上2.7下也应该可以正常使用。有环境的朋友可以帮忙测试一下。
该脚本不完善的地方在于,只能支持一级目录下的文件删除,还不支持目录递归。同时过期文件的定义只能按week来做。
Python代码:
复制代码 代码如下:
import sys
import os
import time,datetime
dir = '/data/webbak/'
logdir = '/var/log'
logfile = os.path.join(logdir, 'delete.log')
ver = sys.version
ver = ver.split(' ')
ver = ver[0]
def string2time(str_time, version = ver):
version_l = version.split('.')[0:2]
ver = version_l[0] + '.' + version_l[1]
if (ver == '2.7'):
f_time = datetime.datetime.strptime(str_time, time_format)
f_time = f_time.strftime('%Y-%m-%d %H:%M:%S')
return f_time
elif(ver == '2.4'):
f_time = time.strptime(str_time, time_format)
f_time = datetime.datetime(*f_time[0:6])
return f_time
time_format = "%a %b %d %H:%M:%S %Y"
today = datetime.datetime.now()
four_weeks = datetime.timedelta(weeks=6)
four_weeks_ago = today - four_weeks
four_weeks_ago_timestamps = time.mktime(four_weeks_ago.timetuple())
files = os.listdir(dir)
fh = open(logfile, "w+")
for f in files:
if f.startswith('.'):
continue
if os.path.isdir(os.path.join(dir,f)):
continue
file_timestamp = os.path.getmtime(os.path.join(dir, f))
file_time_f = string2time(time.ctime(file_timestamp))
if float(file_timestamp) <= float(four_weeks_ago_timestamps):
fh.write(str(today) + "\t" + str(file_time_f) + "\t" + os.path.join(dir,f) + "\n")
os.remove(os.path.join(dir,f))
fh.close()
脚本2:
实现类似下面的Shell命令的操作
复制代码 代码如下:
find /data/log -ctime +5 | xargs rm -f
Python代码:
复制代码 代码如下:
import os
import sys
import time
class DeleteLog:
def __init__(self,fileName,days):
self.fileName = fileName
self.days = days
def delete(self):
if os.path.isfile(self.fileName):
fd = open(self.fileName,'r')
while 1:
buffer = fd.readline()
if not buffer : break
if os.path.isfile(buffer):
os.remove(buffer)
fd.close()
elif os.path.isdir(self.fileName):
for i in [os.sep.join([self.fileName,v]) for v in os.listdir(self.fileName)]:
print i
if os.path.isfile(i):
if self.compare_file_time(i):
os.remove(i)
elif os.path.isdir(i):
self.fileName = i
self.delete()
def compare_file_time(self,file):
time_of_last_access = os.path.getatime(file)
age_in_days = (time.time()-time_of_last_access)/(60*60*24)
if age_in_days > self.days:
return True
return False
if name == 'main':
if len(sys.argv) == 2:
obj = DeleteLog(sys.argv[1],0)
obj.delete()
elif len(sys.argv) == 3:
obj = DeleteLog(sys.argv[1],int(sys.argv[2]))
obj.delete()
else:
print "usage: python %s listFileName|dirName [days]" % sys.argv[0]
sys.exit(1)
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8