44 lines
1.6 KiB
Python
44 lines
1.6 KiB
Python
|
|
import os
|
||
|
|
import shutil
|
||
|
|
import uuid
|
||
|
|
from config import Config
|
||
|
|
from logger import logger
|
||
|
|
|
||
|
|
class TempManager:
|
||
|
|
def __init__(self):
|
||
|
|
self.base_dir = Config.TEMP_DIR
|
||
|
|
self.session_dir = None
|
||
|
|
|
||
|
|
def init_session(self):
|
||
|
|
"""每次运行创建一个新的会话临时目录"""
|
||
|
|
if not os.path.exists(self.base_dir):
|
||
|
|
os.makedirs(self.base_dir)
|
||
|
|
self.session_dir = os.path.join(self.base_dir, f"session_{uuid.uuid4().hex[:8]}")
|
||
|
|
os.makedirs(self.session_dir, exist_ok=True)
|
||
|
|
logger.info(f"创建临时会话目录: {self.session_dir}")
|
||
|
|
return self.session_dir
|
||
|
|
|
||
|
|
def get_subdir(self, name):
|
||
|
|
"""在会话目录下创建子目录"""
|
||
|
|
path = os.path.join(self.session_dir, name)
|
||
|
|
os.makedirs(path, exist_ok=True)
|
||
|
|
return path
|
||
|
|
|
||
|
|
def cleanup(self):
|
||
|
|
"""清理本次会话临时目录"""
|
||
|
|
if self.session_dir and os.path.exists(self.session_dir):
|
||
|
|
shutil.rmtree(self.session_dir, ignore_errors=True)
|
||
|
|
logger.info(f"清理临时目录: {self.session_dir}")
|
||
|
|
|
||
|
|
@staticmethod
|
||
|
|
def cleanup_stale():
|
||
|
|
"""启动时清理所有遗留临时目录(超过1天)"""
|
||
|
|
if os.path.exists(Config.TEMP_DIR):
|
||
|
|
for item in os.listdir(Config.TEMP_DIR):
|
||
|
|
path = os.path.join(Config.TEMP_DIR, item)
|
||
|
|
if os.path.isdir(path) and item.startswith("session_"):
|
||
|
|
try:
|
||
|
|
shutil.rmtree(path)
|
||
|
|
logger.info(f"清理遗留目录: {path}")
|
||
|
|
except Exception as e:
|
||
|
|
logger.warning(f"清理失败 {path}: {e}")
|