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()

猜你喜欢

转载自www.cnblogs.com/huangtao1927/p/python.html
今日推荐