Python指令碼,定時清除大檔案
阿新 • • 發佈:2018-12-25
# !/usr/bin/env python3 # -*- coding:utf-8 -*- import math,os,sys,time import traceback import subprocess ... #定時任務指令碼,清除大於1G的檔案 ... #定義標準檔案大小,預設是位元組 maxFileSize=1024*1024*1024 #定義檔案路徑 files = {"/usr/utils/tomcat9/apache-tomcat-9.0.14/logs/catalina.out":"清除tomcat日誌catalina.out"} #清除大於1G的檔案 def clearLargeFile():for file,message in files.items(): fileSize = getFileSize(file) if int(fileSize) >= maxFileSize: result = os.system("cat /dev/null >" + file) checkResult(result,message) else: print("檔案["+file+"]大小為["+fileSize+"],小於設定的最大值["+str(maxFileSize)+"],無需清空") #獲取檔案大小 def getFileSize(file): linuxCommand = "ls -l " + file + " | awk '{print $5}'" print("獲取檔案大小的linux命令為["+linuxCommand+"]") output,returnCode = executeShell(linuxCommand) return output #執行linux命令獲取返回結果與返回碼 def executeShell(command,print_output=True,universal_newlines=True): p= subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, universal_newlines=universal_newlines) if print_output: output_array = [] while True: line = p.stdout.readline() if not line: break output_array.append(line) output ="".join(output_array) else: output = p.stdout.read() p.wait() errout = p.stderr.read() p.stdout.close() p.stderr.close() return str(output),str(p.returncode) #判斷執行結果 def checkResult(result,message): if result == 0: print(message+"執行成功") else: print(message+"執行失敗") #異常的處理 def handleExcption(e): print("<---The Excption Begin--->") print('\n' * 1) traceback.print_exc() print('\n' * 1) print("<---The Excption End--->") #最終執行的方法 def execute(): print("<---The clearLargeFile.py Begin--->") print('\n' * 1) try: clearLargeFile() except Exception as e: handleExcption(e) print('\n' * 1) print("<---The clearLargeFile.py End--->") #最終執行 execute()