# encoding: utf-8 import sys import getopt import os import glob import time import datetime def removefile(keep=7): for file in glob.glob(‘/app/*/logs/*/*.log‘): # 获取当前时间 today = datetime.datetime.now() # 计算偏移量,前k天 offset = datetime.timedelta(minutes=-keep) # 获取想要的日期时间,即前k天时间 re_date = (today + offset) # 前k天时间转换为时间戳 re_date_unix = time.mktime(re_date.timetuple()) # 文件修改时间 file_time = os.path.getmtime(file) print(file) if file_time <= re_date_unix: os.remove(file) # print("删除文件:" + file) if __name__ == ‘__main__‘: opts, args = getopt.getopt(sys.argv[1:], ‘-h-k:‘, [‘help‘, ‘keep=‘]) if len(opts) == 0: removefile() for opt_name, opt_value in opts: if opt_name in (‘-h‘, ‘--help‘): print("[*] Help info") print("-k n\t\t", "Keep files for n days") sys.exit() if opt_name in (‘-k‘, ‘--keep‘): removefile(keep=eval(opt_value))