Python腳本,定時清除大文件

# !/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()

 

下面是用系統方法python

# !/usr/bin/env python3
# -*- coding:utf-8 -*-  
import math,os,sys,time
import traceback
import subprocess
import datetime
...
#定時任務腳本,清除大於1G的文件

...

#定義標準文件大小,默認是字節,最終設置大小爲1G
maxFileSize=1*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 fileSize >= maxFileSize:
            result = os.system("cat /dev/null >" + file)
            checkResult(result,message)
        else:
            print("文件["+file+"]大小爲["+str(fileSize)+"]字節,小於設置的最大值["+str(maxFileSize)+"]字節,無需清空")
            
#獲取文件大小
def getFileSize(file):
    return os.path.getsize(file)

#執行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,the time is ["+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+"]--->")
    print('\n' * 1)
    try:
        clearLargeFile()
    except Exception as e:
        handleExcption(e)

    print('\n' * 1)
    print("<---The clearLargeFile.py End,the time is ["+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+"]--->")

#最終執行
execute()
相關文章
相關標籤/搜索