近期在是用服务器训练的代码的时候,并未在数据盘上传过多文件,但是已经爆满,为啥呢?
解决方法:
进入数据盘文件目录下输入如下指令:
du -h --max-depth=1 .
发现缓存文件占满。
使用如下指令清理对应的缓存:
rm -rf ./.Trash-0/*
由于不能长时间关注程序得运行情况可使用如下代码,自动清理缓存:
import os
import shutil
import datetime
import logging
import time
import schedule
from pathlib import Path
# 配置日志
log_file = os.path.join(os.getcwd(), "trash_cleanup.log")
logging.basicConfig(
filename=log_file,
level=logging.INFO,
format="%(asctime)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
# 同时显示到控制台
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(message)s")
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
def cleanup_trash():
"""清理当前目录下的 .Trash-0 目录中的所有文件"""
# 获取当前目录下的 .Trash-0 目录的路径
trash_dir = os.path.join(os.getcwd(), ".Trash-0")
logging.info(f"开始清理当前目录下的 .Trash-0 目录: {trash_dir}")
# 检查目录是否存在
if os.path.isdir(trash_dir):
try:
# 统计清理前的文件数量和文件大小
total_size = 0
file_count = 0
files_list = []
for root, dirs, files in os.walk(trash_dir):
for file in files:
file_path = os.path.join(root, file)
try:
file_size = os.path.getsize(file_path)
total_size += file_size
file_count += 1
# 收集文件信息
files_list.append((file_path, file_size))
except Exception:
pass
# 打印清理信息
logging.info(f"清理前: 发现 {file_count} 个文件,总大小: {format_size(total_size)}")
# 打印将被删除的所有文件
if files_list:
logging.info("将被删除的文件列表:")
for file_path, file_size in files_list:
rel_path = os.path.relpath(file_path, trash_dir)
logging.info(f" - {rel_path} ({format_size(file_size)})")
# 遍历并删除目录中的所有内容
deleted_count = 0
for item in os.listdir(trash_dir):
item_path = os.path.join(trash_dir, item)
try:
if os.path.isfile(item_path) or os.path.islink(item_path):
os.unlink(item_path)
deleted_count += 1
elif os.path.isdir(item_path):
dir_file_count = sum(len(files) for _, _, files in os.walk(item_path))
deleted_count += dir_file_count
shutil.rmtree(item_path)
except Exception as e:
logging.error(f"删除 {item_path} 时出错: {e}")
logging.info(f"清理完成: 已删除 {deleted_count} 个文件")
except Exception as e:
logging.error(f"清理过程中出现错误: {e}")
else:
logging.error(f"错误: {trash_dir} 目录不存在")
logging.info("清理结束")
logging.info("-" * 40)
def format_size(size_bytes):
"""将字节大小转换为人类可读格式"""
if size_bytes < 1024:
return f"{size_bytes} B"
elif size_bytes < 1024 * 1024:
return f"{size_bytes/1024:.2f} KB"
elif size_bytes < 1024 * 1024 * 1024:
return f"{size_bytes/(1024*1024):.2f} MB"
else:
return f"{size_bytes/(1024*1024*1024):.2f} GB"
def run_as_daemon():
"""将脚本作为守护进程运行,按计划执行清理任务"""
# 设置每分钟执行一次的计划
# schedule.every(1).minutes.do(cleanup_trash)
# 设置每10分钟执行一次的计划
schedule.every(10).minutes.do(cleanup_trash)
logging.info("启动定时清理服务")
logging.info("设置为每10分钟清理一次")
logging.info("-" * 40)
# 运行循环,持续检查是否有计划任务需要执行
while True:
schedule.run_pending()
time.sleep(1)
if __name__ == "__main__":
import sys
if len(sys.argv) > 1 and sys.argv[1] == "--daemon":
# 作为守护进程运行
run_as_daemon()
else:
# 单次执行清理
cleanup_trash()
在数据盘新建cleanup_trash.py将上述代码粘贴在该文件中。
添加执行权限:
chmod +x cleanup_trash.py
运行方式:
- 单次清理
./cleanup_trash.py
- 作为守护进程运行(每分钟清理):
./cleanup_trash.py --daemon
每次清理时,脚本会在控制台和日志文件中详细列出被删除的文件。如果你想切换到每10分钟清理一次,只需调整代码中的注释部分即可。