最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python實(shí)現(xiàn)自動(dòng)化清理臨時(shí)文件的全攻略

 更新時(shí)間:2026年03月02日 14:39:25   作者:hefeng_aspnet  
這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)自動(dòng)化清理臨時(shí)文件的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

一、臨時(shí)文件的智能識(shí)別系統(tǒng)

1. 文件指紋識(shí)別引擎

import os
import hashlib
import magic 
from pathlib import Path
from datetime import datetime, timedelta
from typing import Dict, List, Set, Optional
import mimetypes
import json

???????class FileFingerprint:
    """文件指紋識(shí)別系統(tǒng) - 智能判斷文件類型和用途"""
    
    def __init__(self):
        self.temp_patterns = {
            'compilation': ['.o', '.obj', '.class', '.pyc', '.pyo'],
            'cache': ['.cache', '.tmp', '.swp', '.swo', '.swn'],
            'log': ['.log', '.out', '.err', '.trace'],
            'download': ['.part', '.crdownload', '.download'],
            'backup': ['~', '.bak', '.backup', '.old'],
            'ide': ['.idea/', '.vscode/', '.vs/', 'thumbs.db'],
            'build': ['node_modules/', '__pycache__/', 'dist/', 'build/']
        }
        
        self.mime = magic.Magic(mime=True)
        self.safe_extensions = {'.py', '.js', '.java', '.cpp', '.md', '.txt'}
        
    def analyze_file(self, filepath: Path) -> Dict:
        """深度分析文件特征"""
        stats = filepath.stat()
        
        fingerprint = {
            'path': str(filepath),
            'size': stats.st_size,
            'created': datetime.fromtimestamp(stats.st_ctime),
            'modified': datetime.fromtimestamp(stats.st_mtime),
            'accessed': datetime.fromtimestamp(stats.st_atime),
            'extension': filepath.suffix.lower(),
            'is_temp': False,
            'category': 'unknown',
            'risk_level': 'low',
            'content_hash': self._calculate_hash(filepath),
            'mime_type': self._detect_mime(filepath)
        }
        
        # 智能分類
        fingerprint.update(self._classify_file(filepath, fingerprint))
        return fingerprint
    
    def _classify_file(self, filepath: Path, fp: Dict) -> Dict:
        """智能文件分類"""
        result = {'category': 'other', 'is_temp': False}
        
        # 基于擴(kuò)展名識(shí)別
        for category, patterns in self.temp_patterns.items():
            for pattern in patterns:
                if pattern.startswith('.') and fp['extension'] == pattern:
                    result.update({'category': category, 'is_temp': True})
                    return result
                elif pattern.endswith('/') and pattern in str(filepath):
                    result.update({'category': category, 'is_temp': True})
                    return result
                elif pattern in filepath.name:
                    result.update({'category': category, 'is_temp': True})
                    return result
        
        # 基于文件名模式識(shí)別
        filename = filepath.name.lower()
        temp_patterns = ['temp', 'tmp', 'cache', 'swap', 'dump']
        if any(pattern in filename for pattern in temp_patterns):
            result.update({'category': 'temp_pattern', 'is_temp': True})
        
        # 基于內(nèi)容識(shí)別(大文件且長時(shí)間未訪問)
        if (fp['size'] > 100 * 1024 * 1024 and  # 大于100MB
            datetime.now() - fp['accessed'] > timedelta(days=30)):
            result.update({'category': 'large_inactive', 'is_temp': True})
        
        return result
    
    def _calculate_hash(self, filepath: Path) -> str:
        """計(jì)算文件內(nèi)容哈希(采樣)"""
        try:
            if filepath.stat().st_size > 10 * 1024 * 1024:  # 大文件采樣
                with open(filepath, 'rb') as f:
                    # 采樣文件頭、中、尾
                    f.seek(0)
                    head = f.read (4096)
                    f.seek(max(0, filepath.stat().st_size // 2 - 2048))
                    middle = f.read(4096)
                    f.seek(max(0, filepath.stat().st_size - 4096))
                    tail = f.read(4096)
                    data  = head + middle + tail
            else:
                data = filepath.read_bytes()
            
            return hashlib.md5(data).hexdigest()
        except:
            return 'error'
    
    def _detect_mime(self, filepath: Path) -> str:
        """檢測文件真實(shí)類型"""
        try:
            return self.mime.from_file(str(filepath))
        except:
            return mimetypes.guess_type(str(filepath))[0] or 'unknown'

2. 目錄掃描與監(jiān)控系統(tǒng)

import psutil
import platform
from dataclasses import dataclass
from collections import defaultdict
import shutil

@dataclass
class ScanResult:
    total_size: int
    file_count: int
    temp_files: List[Dict]
    by_category: Dict[str, List[Dict]]
    disk_usage: Dict

???????class TempFileScanner:
    """臨時(shí)文件掃描器"""
    
    def __init__(self):
        self.fingerprint = FileFingerprint()
        
        # 系統(tǒng)特定的臨時(shí)目錄
        self.system_temp_dirs = self._get_system_temp_dirs()
        
    def _get_system_temp_dirs(self) -> List[Path]:
        """獲取系統(tǒng)臨時(shí)目錄"""
        system = platform.system()
        temp_dirs = []
        
        # 系統(tǒng)臨時(shí)目錄
        if system == 'Windows':
            temp_dirs.extend([
                Path(os.environ.get('TEMP', 'C:\\Windows\\Temp')),
                Path(os.environ.get('TMP', 'C:\\Windows\\Temp')),
                Path('C:\\Users\\') / os.environ['USERNAME'] / 'AppData' / 'Local' / 'Temp'
            ])
        elif system == 'Linux' or system == 'Darwin':
            temp_dirs.extend([
                Path('/tmp'),
                Path('/var/tmp'),
                Path.home() / '.cache',
                Path.home() / '.tmp'
            ])
        
        # 開發(fā)工具臨時(shí)目錄
        dev_tools = [
            Path.home() / '.npm',  # npm緩存
            Path.home() / '.m2',   # Maven倉庫
            Path.home() / '.gradle',  # Gradle緩存
            Path.home() / '.cache/pip',  # pip緩存
            Path.home() / '.cargo/registry',  # Rust緩存
            Path.home() / 'Library/Caches',  # macOS應(yīng)用緩存
        ]
        
        temp_dirs.extend([d for d in dev_tools if d.exists()])
        return temp_dirs
    
    def scan_directory(self, directory: Path, recursive: bool = True) -> ScanResult:
        """掃描目錄中的臨時(shí)文件"""
        temp_files = []
        by_category = defaultdict(list)
        total_size = 0
        file_count = 0
        
        scan_method = directory.rglob if recursive else directory.glob
        
        for filepath in scan_method('*'):
            if filepath.is_file():
                try:
                    fp = self.fingerprint.analyze_file(filepath)
                    file_count += 1
                    total_size += fp['size']
                    
                    if fp['is_temp']:
                        temp_files.append(fp)
                        by_category[fp['category']].append(fp)
                        
                except (PermissionError, OSError):
                    continue
        
        # 獲取磁盤使用情況
        disk_usage = self._get_disk_usage(directory)
        
        return ScanResult(
            total_size=total_size,
            file_count=file_count,
            temp_files=temp_files,
            by_category=dict(by_category),
            disk_usage=disk_usage
        )
    
    def _get_disk_usage(self, path: Path) -> Dict:
        """獲取磁盤使用情況"""
        usage = psutil.disk_usage(str(path))
        return {
            'total': usage.total,
            'used': usage.used,
            'free': usage.free,
            'percent': usage.percent,
            'threshold': 85  # 警告閾值85%
        }
    
    def find_largest_temp_files(self, directory: Path, top_n: int = 20) -> List[Dict]:
        """查找最大的臨時(shí)文件"""
        scanner = self.scan_directory(directory)
        
        # 按大小排序
        sorted_files = sorted(
            scanner.temp_files,
            key=lambda x: x['size'],
            reverse=True
        )
        
        return sorted_files[:top_n]

二、智能清理策略引擎

1. 基于規(guī)則的清理策略

from abc import ABC, abstractmethod
from typing import List, Tuple
import heapq

class CleanupStrategy(ABC):
    """清理策略抽象基類"""
    
    @abstractmethod
    def should_clean(self, file_info: Dict) -> bool:
        pass
    
    @abstractmethod
    def get_priority(self, file_info: Dict) -> int:
        pass

class AgeBasedStrategy(CleanupStrategy):
    """基于時(shí)間的清理策略"""
    
    def __init__(self, max_age_days: int = 7):
        self.max_age = timedelta(days=max_age_days)
    
    def should_clean(self, file_info: Dict) -> bool:
        age = datetime.now() - file_info['modified']
        return age > self.max_age
    
    def get_priority(self, file_info: Dict) -> int:
        age_hours = (datetime.now() - file_info['modified']).total_seconds() / 3600
        return int(age_hours)  # 越舊優(yōu)先級(jí)越高

class SizeBasedStrategy(CleanupStrategy):
    """基于大小的清理策略"""
    
    def __init__(self, min_size_mb: int = 10):
        self.min_size = min_size_mb * 1024 * 1024
    
    def should_clean(self, file_info: Dict) -> bool:
        return file_info['size'] > self.min_size
    
    def get_priority(self, file_info: Dict) -> int:
        # 每100MB得1分
        return file_info['size'] // (100 * 1024 * 1024)

class AccessBasedStrategy(CleanupStrategy):
    """基于訪問頻率的清理策略"""
    
    def __init__(self, min_access_days: int = 30):
        self.min_access = timedelta(days=min_access_days)
    
    def should_clean(self, file_info: Dict) -> bool:
        last_access = datetime.now() - file_info['accessed']
        return last_access > self.min_access
    
    def get_priority(self, file_info: Dict) -> int:
        days_since_access = (datetime.now() - file_info['accessed']).days
        return days_since_access

???????class CompositeStrategy(CleanupStrategy):
    """組合策略 - 加權(quán)評(píng)分"""
    
    def __init__(self):
        self.strategies = [
            (AgeBasedStrategy(max_age_days=7), 0.4),      # 40%權(quán)重
            (SizeBasedStrategy(min_size_mb=50), 0.3),     # 30%權(quán)重
            (AccessBasedStrategy(min_access_days=14), 0.3) # 30%權(quán)重
        ]
    
    def should_clean(self, file_info: Dict) -> bool:
        # 只要有一個(gè)策略認(rèn)為應(yīng)該清理,就返回True
        return any(strategy.should_clean(file_info) 
                  for strategy, _ in self.strategies)
    
    def get_priority(self, file_info: Dict) -> int:
        total_score = 0
        for strategy, weight in self.strategies:
            if strategy.should_clean(file_info):
                score = strategy.get_priority(file_info)
                total_score += int(score * weight * 100)
        return total_score

2. 智能清理管理器

class SmartCleanupManager:
    """智能清理管理器"""
    
    def __init__(self, strategy: CleanupStrategy = None):
        self.strategy = strategy or CompositeStrategy()
        self.scanner = TempFileScanner()
        self.cleaned_files = []
        self.backup_dir = Path.home() / '.temp_cleanup_backup'
        self.backup_dir.mkdir(exist_ok=True)
        
        # 清理歷史記錄
        self.history_file = self.backup_dir / 'cleanup_history.json'
        self.history = self._load_history()
    
    def _load_history(self) -> List:
        """加載清理歷史"""
        if self.history_file.exists():
            with open(self.history_file, 'r') as f:
                return json.load(f)
        return []
    
    def _save_history(self):
        """保存清理歷史"""
        with open(self.history_file, 'w') as f:
            json.dump(self.history[-1000:], f, indent=2, default=str)
    
    def analyze_and_clean(self, directory: Path, 
                         dry_run: bool = True,
                         max_size_to_free: int = 0) -> Dict:
        """分析并清理目錄"""
        print(f"?? 掃描目錄: {directory}")
        
        # 掃描文件
        scan_result = self.scanner.scan_directory(directory)
        
        print(f"?? 掃描結(jié)果:")
        print(f"   總文件數(shù): {scan_result.file_count}")
        print(f"   總大小: {self._format_size(scan_result.total_size)}")
        print(f"   臨時(shí)文件數(shù): {len(scan_result.temp_files)}")
        
        # 應(yīng)用清理策略
        files_to_clean = []
        for file_info in scan_result.temp_files:
            if self.strategy.should_clean(file_info):
                priority = self.strategy.get_priority(file_info)
                files_to_clean.append((priority, file_info))
        
        # 按優(yōu)先級(jí)排序
        files_to_clean.sort(reverse=True)
        
        # 如果指定了要釋放的空間大小
        if max_size_to_free > 0:
            files_to_clean = self._select_files_to_free_space(
                files_to_clean, max_size_to_free
            )
        
        # 執(zhí)行清理
        cleanup_result = self._execute_cleanup(
            [file_info for _, file_info in files_to_clean],
            dry_run
        )
        
        # 更新歷史
        self.history.append({
            'timestamp': datetime.now().isoformat(),
            'directory': str(directory),
            'dry_run': dry_run,
            'result': cleanup_result
        })
        self._save_history()
        
        return cleanup_result
    
    def _select_files_to_free_space(self, files: List[Tuple], 
                                   target_size: int) -> List[Tuple]:
        """選擇文件以釋放目標(biāo)空間大小"""
        selected = []
        freed_size = 0
        
        for priority, file_info in sorted(files, reverse=True):
            if freed_size >= target_size:
                break
            
            selected.append((priority, file_info))
            freed_size += file_info['size']
        
        return selected
    
    def _execute_cleanup(self, files: List[Dict], dry_run: bool) -> Dict:
        """執(zhí)行清理操作"""
        total_freed = 0
        cleaned_count = 0
        errors = []
        
        print(f"\n{'?? 模擬運(yùn)行' if dry_run else '?? 開始清理'}:")
        
        for file_info in files:
            filepath = Path(file_info['path'])
            
            try:
                if dry_run:
                    action = "將刪除"
                else:
                    # 先備份
                    backup_path = self._backup_file(filepath)
                    
                    # 執(zhí)行刪除
                    if filepath.is_file():
                        filepath.unlink()
                    elif filepath.is_dir():
                        shutil.rmtree(filepath)
                
                size_mb = file_info['size'] / (1024 * 1024)
                total_freed += file_info['size']
                cleaned_count += 1
                
                status = "?" if not dry_run else "??"
                print(f"{status} {action} {filepath.name} ({size_mb:.1f}MB)")
                
            except Exception as e:
                errors.append(str(e))
                print(f"? 失敗: {filepath.name} - {e}")
        
        result = {
            'total_freed': total_freed,
            'cleaned_count': cleaned_count,
            'error_count': len(errors),
            'errors': errors,
            'dry_run': dry_run
        }
        
        print(f"\n?? 清理總結(jié):")
        print(f"   釋放空間: {self._format_size(total_freed)}")
        print(f"   清理文件: {cleaned_count}個(gè)")
        if errors:
            print(f"   錯(cuò)誤: {len(errors)}個(gè)")
        
        return result
    
    def _backup_file(self, filepath: Path) -> Path:
        """備份文件(安全措施)"""
        if not filepath.exists():
            return None
        
        # 生成備份路徑
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        relative_path = filepath.relative_to(filepath.anchor)
        safe_name = str(relative_path).replace(os.sep, '_')
        backup_path = self.backup_dir / f"{timestamp}_{safe_name}"
        
        try:
            if filepath.is_file():
                shutil.copy2(filepath, backup_path)
            elif filepath.is_dir():
                shutil.copytree(filepath, backup_path)
        except:
            pass  # 備份失敗也不阻止清理
        
        return backup_path
    
    def _format_size(self, size_bytes: int) -> str:
        """格式化文件大小"""
        for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
            if size_bytes < 1024.0:
                return f"{size_bytes:.2f}{unit}"
            size_bytes /= 1024.0
        return f"{size_bytes:.2f}PB"
    
    def restore_from_backup(self, backup_filename: str) -> bool:
        """從備份恢復(fù)文件"""
        backup_path = self.backup_dir / backup_filename
        if not backup_path.exists():
            return False
        
        # 從備份文件名解析原始路徑
        # 實(shí)現(xiàn)恢復(fù)邏輯...
        return True

三、自動(dòng)化監(jiān)控與調(diào)度系統(tǒng)

1. 實(shí)時(shí)監(jiān)控守護(hù)進(jìn)程

import time
import threading
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import schedule

class TempFileMonitor(FileSystemEventHandler):
    """臨時(shí)文件監(jiān)控器"""
    
    def __init__(self, cleanup_manager: SmartCleanupManager):
        self.manager = cleanup_manager
        self.temp_extensions = {'.tmp', '.temp', '.cache', '.log'}
        self.recent_creations = {}
        
    def on_created(self, event):
        """監(jiān)控新創(chuàng)建的文件"""
        if not event.is_directory:
            filepath = Path(event.src_path)
            if filepath.suffix in self.temp_extensions:
                self.recent_creations[filepath] = time.time()
                print(f"?? 檢測到臨時(shí)文件: {filepath.name}")
                
                # 如果文件超過1小時(shí)未修改,標(biāo)記為可清理
                threading.Timer(3600, self._check_if_stale, args=[filepath]).start()
    
    def on_modified(self, event):
        """文件修改時(shí)更新訪問時(shí)間"""
        if not event.is_directory:
            filepath = Path(event.src_path)
            if filepath in self.recent_creations:
                self.recent_creations[filepath] = time.time()
    
    def _check_if_stale(self, filepath: Path):
        """檢查文件是否已過期"""
        if filepath in self.recent_creations:
            create_time = self.recent_creations[filepath]
            if time.time() - create_time > 3600:  # 1小時(shí)
                if filepath.exists():
                    print(f"? 文件已過期: {filepath.name}")
                    # 自動(dòng)清理
                    self.manager.analyze_and_clean(
                        filepath.parent,
                        dry_run=False,
                        max_size_to_free=0
                    )

???????class AutomatedCleanupScheduler:
    """自動(dòng)化清理調(diào)度器"""
    
    def __init__(self):
        self.manager = SmartCleanupManager()
        self.monitor = TempFileMonitor(self.manager)
        self.observer = Observer()
        
        # 監(jiān)控的目錄
        self.watch_dirs = [
            Path.home() / 'Downloads',
            Path.home() / 'Desktop',
            Path('/tmp') if platform.system() != 'Windows' else 
            Path(os.environ.get('TEMP', 'C:\\Windows\\Temp'))
        ]
    
    def start_monitoring(self):
        """啟動(dòng)文件監(jiān)控"""
        for directory in self.watch_dirs:
            if directory.exists():
                self.observer.schedule(
                    self.monitor,
                    str(directory),
                    recursive=True
                )
                print(f"?? 開始監(jiān)控: {directory}")
        
        self.observer.start()
        
        # 定時(shí)任務(wù)
        schedule.every().day.at("02:00").do(self._nightly_cleanup)
        schedule.every().hour.do(self._check_disk_usage)
        
        print("?? 臨時(shí)文件監(jiān)控器已啟動(dòng)")
        
        try:
            while True:
                schedule.run_pending()
                time.sleep(60)
        except KeyboardInterrupt:
            self.observer.stop()
        self.observer.join()
    
    def _nightly_cleanup(self):
        """夜間自動(dòng)清理"""
        print("?? 執(zhí)行夜間清理...")
        for directory in self.watch_dirs:
            if directory.exists():
                self.manager.analyze_and_clean(
                    directory,
                    dry_run=False,
                    max_size_to_free=1024 * 1024 * 1024  # 嘗試釋放1GB
                )
    
    def _check_disk_usage(self):
        """檢查磁盤使用率"""
        for directory in self.watch_dirs:
            if directory.exists():
                usage = psutil.disk_usage(str(directory))
                if usage.percent > 85:  # 磁盤使用率超過85%
                    print(f"??  磁盤空間不足: {directory} ({usage.percent}%)")
                    # 緊急清理
                    self.manager.analyze_and_clean(
                        directory,
                        dry_run=False,
                        max_size_to_free=1024 * 1024 * 1024 * 5  # 嘗試釋放5GB
                    )

2. 命令行工具集成

import argparse
import sys
from rich.console import Console
from rich.table import Table
from rich.progress import Progress

console = Console()

???????def main():
    parser = argparse.ArgumentParser(
        description='智能臨時(shí)文件清理工具',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""

使用示例:

  %(prog)s scan ~/Downloads              # 掃描目錄
  %(prog)s clean ~/Downloads --dry-run   # 模擬清理
  %(prog)s clean ~/Downloads --force     # 實(shí)際清理
  %(prog)s monitor                       # 啟動(dòng)監(jiān)控守護(hù)進(jìn)程
  %(prog)s stats                         # 顯示統(tǒng)計(jì)信息
        """
    )
    
    subparsers = parser.add_subparsers(dest='command', help='命令')
    
    # scan 命令
    scan_parser = subparsers.add_parser('scan', help='掃描臨時(shí)文件')
    scan_parser.add_argument('directory', help='要掃描的目錄')
    scan_parser.add_argument('--recursive', '-r', action='store_true', 
                           help='遞歸掃描')
    scan_parser.add_argument('--top', type=int, default=20,
                           help='顯示最大的N個(gè)文件')
    
    # clean 命令
    clean_parser = subparsers.add_parser('clean', help='清理臨時(shí)文件')
    clean_parser.add_argument('directory', help='要清理的目錄')
    clean_parser.add_argument('--dry-run', '-d', action='store_true',
                            help='模擬運(yùn)行,不實(shí)際刪除')
    clean_parser.add_argument('--force', '-f', action='store_true',
                            help='強(qiáng)制清理,無需確認(rèn)')
    clean_parser.add_argument('--free-size', type=int,
                            help='要釋放的空間大小(MB)')
    
    # monitor 命令
    subparsers.add_parser('monitor', help='啟動(dòng)監(jiān)控守護(hù)進(jìn)程')
    
    # stats 命令
    stats_parser = subparsers.add_parser('stats', help='顯示統(tǒng)計(jì)信息')
    stats_parser.add_argument('--days', type=int, default=7,
                            help='顯示最近N天的統(tǒng)計(jì)')
    
    args = parser.parse_args()
    
    if args.command == 'scan':
        run_scan(args)
    elif args.command == 'clean':
        run_clean(args)
    elif args.command == 'monitor':
        run_monitor(args)
    elif args.command == 'stats':
        run_stats(args)
    else:
        parser.print_help()

def run_scan(args):
    """執(zhí)行掃描命令"""
    scanner = TempFileScanner()
    directory = Path(args.directory).expanduser()
    
    if not directory.exists():
        console.print(f"[red]目錄不存在: {directory}[/red]")
        return
    
    console.print(f"[bold blue]掃描目錄: {directory}[/bold blue]")
    
    with Progress() as progress:
        task = progress.add_task("[cyan]掃描中...", total=None)
        
        # 掃描文件
        result = scanner.scan_directory(directory, args.recursive)
        
        progress.update(task, completed=100)
    
    # 顯示結(jié)果表格
    table = Table(title="臨時(shí)文件分析結(jié)果")
    table.add_column("分類", style="cyan")
    table.add_column("文件數(shù)", justify="right")
    table.add_column("總大小", justify="right")
    table.add_column("占比", justify="right")
    
    for category, files in result.by_category.items():
        category_size = sum(f['size'] for f in files)
        percentage = (category_size / result.total_size * 100) if result.total_size > 0 else 0
        
        table.add_row(
            category,
            str(len(files)),
            scanner._format_size(category_size),
            f"{percentage:.1f}%"
        )
    
    console.print(table)
    
    # 顯示最大的文件
    if args.top > 0:
        largest_files = scanner.find_largest_temp_files(directory, args.top)
        
        if largest_files:
            console.print(f"\n[bold yellow]最大的 {args.top} 個(gè)臨時(shí)文件:[/bold yellow]")
            file_table = Table()
            file_table.add_column("文件名", style="green")
            file_table.add_column("大小", justify="right")
            file_table.add_column("修改時(shí)間", justify="right")
            file_table.add_column("分類", style="cyan")
            
            for file_info in largest_files:
                file_table.add_row(
                    Path(file_info['path']).name,
                    scanner._format_size(file_info['size']),
                    file_info['modified'].strftime('%Y-%m-%d %H:%M'),
                    file_info['category']
                )
            
            console.print(file_table)

def run_clean(args):
    """執(zhí)行清理命令"""
    manager = SmartCleanupManager()
    directory = Path(args.directory).expanduser()
    
    if not directory.exists():
        console.print(f"[red]目錄不存在: {directory}[/red]")
        return
    
    # 確認(rèn)(除非使用--force)
    if not args.force and not args.dry_run:
        console.print(f"[bold yellow]警告: 將清理目錄: {directory}[/bold yellow]")
        response = input("確定繼續(xù)嗎? (y/N): ")
        if response.lower() != 'y':
            console.print("[red]操作已取消[/red]")
            return
    
    console.print(f"[bold blue]開始清理: {directory}[/bold blue]")
    
    # 執(zhí)行清理
    result = manager.analyze_and_clean(
        directory,
        dry_run=args.dry_run,
        max_size_to_free=(args.free_size * 1024 * 1024) if args.free_size else 0
    )
    
    if result['dry_run']:
        console.print(f"[yellow]模擬運(yùn)行完成,可釋放 {manager._format_size(result['total_freed'])}[/yellow]")
    else:
        console.print(f"[green]清理完成,已釋放 {manager._format_size(result['total_freed'])}[/green]")

def run_monitor(args):
    """啟動(dòng)監(jiān)控守護(hù)進(jìn)程"""
    scheduler = AutomatedCleanupScheduler()
    console.print("[bold green]啟動(dòng)臨時(shí)文件監(jiān)控守護(hù)進(jìn)程...[/bold green]")
    console.print("按 Ctrl+C 停止監(jiān)控")
    scheduler.start_monitoring()

def run_stats(args):
    """顯示統(tǒng)計(jì)信息"""
    manager = SmartCleanupManager()
    
    if manager.history:
        console.print("[bold blue]清理歷史統(tǒng)計(jì):[/bold blue]")
        
        table = Table()
        table.add_column("時(shí)間", style="cyan")
        table.add_column("目錄")
        table.add_column("釋放空間", justify="right")
        table.add_column("清理文件", justify="right")
        
        for record in manager.history[-args.days:]:
            table.add_row(
                record['timestamp'][:16],
                Path(record['directory']).name,
                manager._format_size(record['result']['total_freed']),
                str(record['result']['cleaned_count'])
            )
        
        console.print(table)
        
        # 計(jì)算總計(jì)
        total_freed = sum(r['result']['total_freed'] for r in manager.history)
        total_files = sum(r['result']['cleaned_count'] for r in manager.history)
        
        console.print(f"\n[bold green]總計(jì):[/bold green]")
        console.print(f"  釋放空間: {manager._format_size(total_freed)}")
        console.print(f"  清理文件: {total_files}個(gè)")
    else:
        console.print("[yellow]暫無清理歷史記錄[/yellow]")

if __name__ == '__main__':
    main()

四、使用示例與最佳實(shí)踐

1. 基本使用示例

from pathlib import Path

# 創(chuàng)建清理管理器
manager = SmartCleanupManager()

# 掃描Downloads目錄
downloads = Path.home() / 'Downloads'
result = manager.scan_directory(downloads)

print(f"找到 {len(result.temp_files)} 個(gè)臨時(shí)文件")
print(f"總大小: {manager._format_size(result.total_size)}")

2. 智能清理配置

# 自定義策略:清理超過100MB且7天未訪問的文件
custom_strategy = CompositeStrategy()
manager = SmartCleanupManager(custom_strategy)

3. 自動(dòng)化監(jiān)控

# 創(chuàng)建監(jiān)控調(diào)度器
scheduler = AutomatedCleanupScheduler()

???????# 添加自定義監(jiān)控目錄
scheduler.watch_dirs.append(Path.home() / 'Projects' / 'builds')

4. 安全備份與恢復(fù)

#清理前自動(dòng)備份
manager.backup_dir = Path.home() / '.safe_cleanup_backups'

# 查看可恢復(fù)的備份
backup_files = list(manager.backup_dir.glob('*.backup'))
for backup in backup_files[:5]:
    print(f"備份: {backup.name}")

5. 集成到開發(fā)工作流

# 在構(gòu)建腳本中添加清理
def build_project():
    # 構(gòu)建前清理臨時(shí)文件
    cleanup_tool = SmartCleanupManager()
    cleanup_tool.analyze_and_clean(
        Path('build'),
        dry_run=False
    )
    
    # 執(zhí)行構(gòu)建
    # ... 構(gòu)建代碼
    
    # 構(gòu)建后清理
    cleanup_tool.analyze_and_clean(
        Path('dist'),
        dry_run=False
    )

五、安全注意事項(xiàng)

class SafeCleanupValidator:
    """安全驗(yàn)證器 - 防止誤刪重要文件"""
    
    SAFE_PATTERNS = {
        'git': ['.git/', '.gitignore', '.gitmodules'],
        'config': ['.env', 'config.', 'settings.', 'secret'],
        'database': ['.db', '.sqlite', '.mdb'],
        'project': ['package.json', 'requirements.txt', 'pom.xml']
    }
    
    def __init__(self):
        self.whitelist = self._load_whitelist()
    
    def _load_whitelist(self):
        """加載白名單"""
        whitelist_file = Path.home() / '.cleanup_whitelist.txt'
        if whitelist_file.exists():
            return set(whitelist_file.read_text().splitlines())
        return set()
    
    def is_safe_to_delete(self, filepath: Path) -> bool:
        """檢查文件是否可以安全刪除"""
        # 檢查白名單
        if str(filepath) in self.whitelist:
            return False
        
        # 檢查安全模式
        for category, patterns in self.SAFE_PATTERNS.items():
            for pattern in patterns:
                if pattern in str(filepath):
                    return False
        
        # 檢查文件內(nèi)容(簡單啟發(fā)式)
        try:
            if filepath.stat().st_size < 1024:  # 小文件
                content = filepath.read_text()[:500]
                dangerous_keywords = ['password', 'secret', 'key', 'token']
                if any(keyword in content.lower() for keyword in dangerous_keywords):
                    return False
        except:
            pass
        
        return True
    
    def add_to_whitelist(self, filepath: Path):
        """添加文件到白名單"""
        self.whitelist.add(str(filepath))
        self._save_whitelist()
    
    def _save_whitelist(self):
        """保存白名單"""
        whitelist_file = Path.home() / '.cleanup_whitelist.txt'
        whitelist_file.write_text('\n'.join(sorted(self.whitelist)))

這個(gè)完整的臨時(shí)文件管理工具提供了:

  • 智能識(shí)別 - 準(zhǔn)確識(shí)別臨時(shí)文件
  • 安全清理 - 多重驗(yàn)證防止誤刪
  • 自動(dòng)化監(jiān)控 - 實(shí)時(shí)監(jiān)控和定時(shí)清理
  • 可視化報(bào)告 - 清晰的統(tǒng)計(jì)信息
  • 備份恢復(fù) - 安全網(wǎng)機(jī)制

以上就是Python實(shí)現(xiàn)自動(dòng)化清理臨時(shí)文件的全攻略的詳細(xì)內(nèi)容,更多關(guān)于Python清理文件的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • python基于機(jī)器學(xué)習(xí)預(yù)測股票交易信號(hào)

    python基于機(jī)器學(xué)習(xí)預(yù)測股票交易信號(hào)

    近年來,隨著技術(shù)的發(fā)展,機(jī)器學(xué)習(xí)和深度學(xué)習(xí)在金融資產(chǎn)量化研究上的應(yīng)用越來越廣泛和深入。目前,大量數(shù)據(jù)科學(xué)家在Kaggle網(wǎng)站上發(fā)布了使用機(jī)器學(xué)習(xí)/深度學(xué)習(xí)模型對(duì)股票、期貨、比特幣等金融資產(chǎn)做預(yù)測和分析的文章。本文就來看看如何用python預(yù)測股票交易信號(hào)
    2021-05-05
  • python算法學(xué)習(xí)雙曲嵌入論文代碼實(shí)現(xiàn)數(shù)據(jù)集介紹

    python算法學(xué)習(xí)雙曲嵌入論文代碼實(shí)現(xiàn)數(shù)據(jù)集介紹

    由于雙曲嵌入相關(guān)的文章已經(jīng)有了一系列的代碼。本篇博客主要目的實(shí)現(xiàn)最開始的雙曲嵌入論文,將論文中有些直接寫出來的內(nèi)容進(jìn)行了細(xì)節(jié)的推導(dǎo),同時(shí)實(shí)現(xiàn)對(duì)應(yīng)的代碼
    2021-11-11
  • 詳解Python實(shí)現(xiàn)URL監(jiān)測與即時(shí)推送

    詳解Python實(shí)現(xiàn)URL監(jiān)測與即時(shí)推送

    這篇文章主要為大家介紹了Python實(shí)現(xiàn)URL監(jiān)測與即時(shí)推送,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2021-11-11
  • 利用Python抓取行政區(qū)劃碼的方法

    利用Python抓取行政區(qū)劃碼的方法

    做項(xiàng)目的時(shí)候會(huì)需要用到各個(gè)行政區(qū)劃的代碼,最近就碰巧遇到有這個(gè)需求,于是就上網(wǎng)搜了一下,測試后分享給大家,這篇文章就給大家分享了利用Python抓取行政區(qū)劃碼的示例代碼,有需要的朋友們可以參考借鑒,下面跟著小編一起去學(xué)習(xí)學(xué)習(xí)吧。
    2016-11-11
  • 使用PyCharm安裝pytest及requests的問題

    使用PyCharm安裝pytest及requests的問題

    這篇文章主要介紹了使用PyCharm安裝pytest及requests的相關(guān)資料,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-07-07
  • pip install python 快速安裝模塊的教程圖解

    pip install python 快速安裝模塊的教程圖解

    這篇文章主要介紹了pip install python 如何快速安裝模塊,本文圖文并茂給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-10-10
  • Python一行代碼實(shí)現(xiàn)生成和讀取二維碼

    Python一行代碼實(shí)現(xiàn)生成和讀取二維碼

    二維碼被稱為快速響應(yīng)碼,可能看起來很簡單,但它們能夠存儲(chǔ)大量數(shù)據(jù)。無論掃描二維碼時(shí)包含多少數(shù)據(jù),用戶都可以立即訪問信息。本文將用一行Python代碼實(shí)現(xiàn)二維碼的讀取與生成,需要的可以參考一下
    2022-02-02
  • Opencv python 圖片生成視頻的方法示例

    Opencv python 圖片生成視頻的方法示例

    這篇文章主要介紹了Opencv python 圖片生成視頻的方法示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • 一文系統(tǒng)梳理Python類的特殊方法體系

    一文系統(tǒng)梳理Python類的特殊方法體系

    在Python中,特殊方法,又稱魔術(shù)方法或雙下方法,是定義類行為的強(qiáng)大工具,本文將系統(tǒng)梳理Python類中的特殊方法體系,希望幫助大家寫出更優(yōu)雅的Python代碼
    2025-11-11
  • Django 響應(yīng)數(shù)據(jù)response的返回源碼詳解

    Django 響應(yīng)數(shù)據(jù)response的返回源碼詳解

    這篇文章主要介紹了Django 響應(yīng)數(shù)據(jù)response的返回源碼詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-08-08

最新評(píng)論

三原县| 乌拉特中旗| 邵武市| 鱼台县| 左权县| 虎林市| 汝州市| 伊宁县| 宁晋县| 兰坪| 天津市| 泰宁县| 兖州市| 安福县| 华阴市| 丹棱县| 通河县| 抚顺县| 石河子市| 通许县| 垦利县| 湖州市| 图们市| 定边县| 贵州省| 兰西县| 吉隆县| 平邑县| 武邑县| 阿克苏市| 和硕县| 江油市| 河间市| 正安县| 松阳县| 建始县| 富宁县| 侯马市| 潜山县| 临沭县| 珠海市|