zoukankan      html  css  js  c++  java
  • python脚本自动删除老文件

    #!/usr/bin/env python2
    #-*- coding:UTF-8 -*-
    import subprocess
    import os
    import datetime
    
    #python获取磁盘信息
    
    #磁盘最大使用阈值
    max_size = 20
    abs_path="/root"
    temp_str="test"
    
    #定义删除日志文件
    del_log = "del_log.txt"
    
    #检查是否要删除文件
    def is_del():
    	exec_info = subprocess.check_output("df -h /",shell=True)
    	disk_info = exec_info.split(' ')[-2].split('%')[0]
    	#获取指定目录文件信息,并排序
    	files = sorted([item for item in os.listdir(abs_path) if item.startswith(temp_str)])
    	if int(disk_info) > int(max_size):
    		if len(files)>0:
    			del_name(os.path.join(abs_path,files[0]))
    	else:
    		return 0
    
    #写日志文件装饰器
    def write_log(func):
    	def wrapper(file):
    		del_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    		context = "{} {} 文件已删除 ---->by python
    ".format(del_time,file)
    		with open(os.path.join(abs_path,del_log),"a+") as f:
    			f.writelines(context)
    		print file
    		return func(file)
    	return wrapper
    #执行删除老文件命令
    @write_log
    def del_name(file):
    	#删除指定文件
    	os.remove(file)
    
    def main():
    	is_del()
    
    
    if __name__ == '__main__':
    	main()
    

  • 相关阅读:
    ftp服务器架设
    samba服务器架设
    apache安装
    yum及prm安装
    redis安装与使用
    memcached安装与使用
    mysql主从服务器
    nginx负载均衡服务器搭建
    lnmp环境搭建
    linux笔记
  • 原文地址:https://www.cnblogs.com/anyux/p/11936618.html
Copyright © 2011-2022 走看看