import os def sub_dirs(rdir): li = os.listdir(rdir) return li def main(rdir): content = sub_dirs(rdir) for i in content: i = os.path.join(rdir,i) if os.path.isdir(i): main(i) else: print(i) main('/home/tvrecord')
#!/usr/bin/env python # -*- coding:utf-8 -*- import os import time import sys import logging import datetime import threading # 檢測目錄 ROOT_DIR = '/data2/log2/' # 保留10天文件 SAVE_DATE = 10 # 開始時間小時 START_HOUR = 2 # 開始時間分鐘 START_MINUTE = 00 def daemon(): import os # create - fork 1 try: pid = os.fork() if pid > 0: return pid except OSError as error: logging.error('fork #1 failed: %d (%s)' % (error.errno, error.strerror)) return -1 # it separates the son from the father os.chdir('/opt/pbx') os.setsid() os.umask(0) # create - fork 2 try: pid = os.fork() if pid > 0: return pid except OSError as error: logging.error('fork #2 failed: %d (%s)' % (error.errno, error.strerror)) return -1 sys.stdout.flush() sys.stderr.flush() si = open("/dev/null", 'r') so = open("/dev/null", 'ab') se = open("/dev/null", 'ab', 0) os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) return 0 def set_log(): logging.basicConfig(filename="/data2/log2/delete_log", level=logging.INFO, format="%(asctime)s [%(filename)s:%(lineno)d] %(message)s", datefmt="%m/%d/%Y %H:%M:%S [%A]") def sub_dirs(rdir): ''' 獲取目錄下全部文件 :param rdir: :return: ''' li = os.listdir(rdir) return li def get_files(rdir): ''' 獲取文件路徑 :param rdir: :return:/data2/log2/ariservice7/ari.log.10 ''' content = sub_dirs(rdir) for i in content: i = os.path.join(rdir, i) if os.path.isdir(i): yield from get_files(i) else: yield i def timer(): ''' 設置定時 :return: ''' _date = datetime.datetime.now() excute_time = '%s %s:%s' % (time.strftime('%Y-%m-%d'), START_HOUR, START_MINUTE) excute_time = time.strptime(excute_time, '%Y-%m-%d %H:%M') excute_time = time.mktime(excute_time) if _date.hour > START_HOUR: excute_time += 24 * 60 * 60 elif _date.hour == START_HOUR and _date.minute >= START_MINUTE: excute_time += 24 * 60 * 60 logging.info('timer wait %s', excute_time - time.time()) timer = threading.Timer(excute_time - time.time(), execute, ) timer.start() def execute(): ''' 主任務 :return: ''' delete_time = time.time() - 24*60*60*SAVE_DATE logging.info('delete time[%s]',delete_time) for file in get_files(ROOT_DIR): file_time = os.path.getmtime(file) logging.info('prepare delete file[%s] delete_time[%s] file_time[%s]',file,delete_time,file_time) if file_time < delete_time: os.remove(file) logging.info('deleted file[%s]',file) time.sleep(1) timer() def main(): set_log() pid = daemon() if pid: return pid execute() if __name__ == '__main__': main()