Python实现安全清理各种系统垃圾文件

Written by

in

文章目录
  • 随着时间的推移,计算机会积累大量的临时文件、缓存文件、日志文件和其他不必要的数据,这些文件不仅占用宝贵的存储空间,还可能影响系统的性能。定期清理这些无用文件是系统维护的重要环节。本文将介绍一个实用的Python脚本——系统清理工具,它可以安全地清理各种系统垃圾文件,帮助用户释放存储空间并提升系统性能。
  • 这个系统清理工具具有以下核心功能: 多类型文件清理:支持清理临时文件、缓存文件、日志文件、回收站等 跨平台支持:支持Windows、Linux和macOS操作系统 安全清理机制:提供预览模式,避免误删重要文件 自定义清理规则:支持自定义要清理的文件类型和目录 磁盘空间统计:显示清理前后磁盘空间的变化 日志记录:记录清理操作的详细信息 定时任务支持:可以集成到定时任务中定期清理系统 白名单保护:支持设置白名单,保护重要文件不被误删
  • 这个工具适用于以下场景: 日常系统维护:定期清理系统垃圾文件 存储空间优化:释放磁盘空间,特别是存储空间紧张时 性能优化:清理过多的临时文件以提升系统性能 系统准备:在系统迁移或重装前清理无用文件 故障排查:清理可能引起问题的缓存文件 隐私保护:清理浏览历史、临时文件等隐私相关数据
  • 脚本包含了完善的错误处理机制: 权限验证:检查是否有足够的权限访问和删除文件 路径安全性检查:验证要清理的路径是否安全,防止误删系统关键文件 文件锁定处理:处理被其他程序占用的文件 磁盘空间检查:在操作前检查是否有足够的磁盘空间 异常捕获:捕获并处理运行过程中可能出现的各种异常 回滚机制:在必要时提供操作回滚功能
  • import os import sys import argparse import json import shutil import tempfile from datetime import datetime, timedelta import platform import glob class SystemCleaner: def __init__(self): self.os_type = platform.system().lower() self.cleanup_rules = [] self.whitelist = set() self.cleaned_files = [] self.cleaned_size = 0 self.errors = [] # 默认清理规则 self._set_default_rules() def _set_default_rules(self): “””设置默认清理规则””” if self.os_type == ‘windows’: # Windows系统默认清理规则 self.cleanup_rules.extend([ { ‘name’: ‘临时文件’, ‘paths’: [ os.environ.get(‘TEMP’, ”), os.path.join(os.environ.get(‘SYSTEMROOT’, ”), ‘Temp’), os.path.expanduser(‘~\AppData\Local\Temp’) ], ‘patterns’: [‘*’], ‘age_days’: 7 }, { ‘name’: ‘回收站’, ‘paths’: [os.path.join(drive + ‘:\’, ‘$Recycle.Bin’) for drive in ‘CDEFGHIJKLMNOPQRSTUVWXYZ’], ‘patterns’: [‘*’], ‘age_days’: 30 }, { ‘name’: ‘浏览器缓存’, ‘paths’: [ os.path.expanduser(‘~\AppData\Local\Google\Chrome\User Data\Default\Cache’), os.path.expanduser(‘~\AppData\Local\Mozilla\Firefox\Profiles\*\cache2’), os.path.expanduser(‘~\AppData\Local\Microsoft\Edge\User Data\Default\Cache’) ], ‘patterns’: [‘*’], ‘age_days’: 7 } ]) elif self.os_type == ‘linux’: # Linux系统默认清理规则 self.cleanup_rules.extend([ { ‘name’: ‘临时文件’, ‘paths’: [‘/tmp’, ‘/var/tmp’], ‘patterns’: [‘*’], ‘age_days’: 7 }, { ‘name’: ‘用户缓存’, ‘paths’: [os.path.expanduser(‘~/.cache’)], ‘patterns’: [‘*’], ‘age_days’: 30 }, { ‘name’: ‘日志文件’, ‘paths’: [‘/var/log’], ‘patterns’: [‘*.log.*’, ‘*.gz’], ‘age_days’: 30 } ]) elif self.os_type == ‘darwin’: # macOS # macOS系统默认清理规则 self.cleanup_rules.extend([ { ‘name’: ‘临时文件’, ‘paths’: [‘/tmp’, ‘/var/tmp’], ‘patterns’: [‘*’], ‘age_days’: 7 }, { ‘name’: ‘用户缓存’, ‘paths’: [os.path.expanduser(‘~/Library/Caches’)], ‘patterns’: [‘*’], ‘age_days’: 30 }, { ‘name’: ‘日志文件’, ‘paths’: [os.path.expanduser(‘~/Library/Logs’)], ‘patterns’: [‘*.log.*’], ‘age_days’: 30 } ]) def add_whitelist(self, paths): “””添加白名单路径””” if isinstance(paths, str): paths = [paths] for path in paths: self.whitelist.add(os.path.abspath(path)) def load_config(self, config_file): “””从配置文件加载清理规则””” try: with open(config_file, ‘r’, encoding=’utf-8′) as f: config = json.load(f) # 加载清理规则 if ‘cleanup_rules’ in config: self.cleanup_rules = config[‘cleanup_rules’] # 加载白名单 if ‘whitelist’ in config: self.add_whitelist(config[‘whitelist’]) return True except Exception as e: self.errors.append(f”加载配置文件失败: {e}”) return False def save_config(self, config_file): “””保存配置到文件””” try: config = { ‘cleanup_rules’: self.cleanup_rules, ‘whitelist’: list(self.whitelist) } with open(config_file, ‘w’, encoding=’utf-8′) as f: json.dump(config, f, indent=2, ensure_ascii=False) return True except Exception as e: self.errors.append(f”保存配置文件失败: {e}”) return False def format_bytes(self, bytes_value): “””格式化字节单位””” for unit in [‘B’, ‘KB’, ‘MB’, ‘GB’, ‘TB’]: if bytes_value < 1024.0: return f”{bytes_value:.2f} {unit}” bytes_value /= 1024.0 return f”{bytes_value:.2f} PB” def is_safe_path(self, path): “””检查路径是否安全””” # 检查是否在白名单中 abs_path = os.path.abspath(path) for whitelist_path in self.whitelist: if abs_path.startswith(whitelist_path): return False # 检查是否是系统关键目录 critical_paths = [] if self.os_type == ‘windows’: system_root = os.environ.get(‘SYSTEMROOT’, ‘C:\Windows’) critical_paths = [system_root, ‘C:\Program Files’, ‘C:\Program Files (x86)’] elif self.os_type in [‘linux’, ‘darwin’]: critical_paths = [‘/bin’, ‘/sbin’, ‘/usr/bin’, ‘/usr/sbin’, ‘/etc’, ‘/boot’] for critical_path in critical_paths: if abs_path.startswith(critical_path): return False return True def get_file_age(self, filepath): “””获取文件年龄(天数)””” try: file_time = os.path.getmtime(filepath) file_datetime = datetime.fromtimestamp(file_time) age = datetime.now() – file_datetime return age.days except: return 0 def match_patterns(self, filename, patterns): “””检查文件名是否匹配模式””” for pattern in patterns: if glob.fnmatch.fnmatch(filename, pattern): return True return False def scan_files(self, rule): “””扫描符合规则的文件””” found_files = [] for path in rule[‘paths’]: if not path or not os.path.exists(path): continue try: # 递归遍历目录 for root, dirs, files in os.walk(path): # 跳过隐藏目录 dirs[:] = [d for d in dirs if not d.startswith(‘.’)] for filename in files: # 跳过隐藏文件 if filename.startswith(‘.’): continue filepath = os.path.join(root, filename) # 检查文件是否匹配模式 if not self.match_patterns(filename, rule[‘patterns’]): continue # 检查文件年龄 if ‘age_days’ in rule: file_age = self.get_file_age(filepath) if file_age < rule[‘age_days’]: continue # 检查路径安全性 if not self.is_safe_path(filepath): continue # 获取文件大小 try: file_size = os.path.getsize(filepath) except: file_size = 0 found_files.append({ ‘path’: filepath, ‘size’: file_size, ‘age’: self.get_file_age(filepath) }) except Exception as e: self.errors.append(f”扫描目录 {path} 时出错: {e}”) return found_files def preview_cleanup(self): “””预览清理操作””” print(“系统清理预览”) print(“=” * 60) print(f”操作系统: {self.os_type}”) print() total_files = 0 total_size = 0 for rule in self.cleanup_rules: print(f”清理规则: {rule[‘name’]}”) files = self.scan_files(rule) if files: rule_size = sum(f[‘size’] for f in files) print(f” 发现文件: {len(files)} 个”) print(f” 预计释放: {self.format_bytes(rule_size)}”) total_files += len(files) total_size += rule_size # 显示前10个文件作为示例 print(” 文件示例:”) for i, file_info in enumerate(files[:10]): print(f” {file_info[‘path’]} ({self.format_bytes(file_info[‘size’])}, {file_info[‘age’]}天)”) if len(files) > 10: print(f” … 还有 {len(files) – 10} 个文件”) else: print(” 未发现符合条件的文件”) print() print(f”总计:”) print(f” 文件数量: {total_files}”) print(f” 预计释放: {self.format_bytes(total_size)}”) return total_files, total_size def perform_cleanup(self, dry_run=True): “””执行清理操作””” print(f”{‘预览’ if dry_run else ‘执行’}系统清理”) print(“=” * 60) self.cleaned_files = [] self.cleaned_size = 0 cleaned_count = 0 for rule in self.cleanup_rules: print(f”处理规则: {rule[‘name’]}”) files = self.scan_files(rule) for file_info in files: filepath = file_info[‘path’] filesize = file_info[‘size’] if dry_run: print(f” 将删除: {filepath} ({self.format_bytes(filesize)})”) else: try: os.remove(filepath) print(f” 已删除: {filepath}”) self.cleaned_files.append(filepath) self.cleaned_size += filesize cleaned_count += 1 except Exception as e: error_msg = f”删除文件 {filepath} 失败: {e}” print(f” 错误: {error_msg}”) self.errors.append(error_msg) print() if not dry_run: print(f”清理完成:”) print(f” 删除文件: {cleaned_count} 个”) print(f” 释放空间: {self.format_bytes(self.cleaned_size)}”) return cleaned_count, self.cleaned_size def clean_empty_dirs(self, dry_run=True): “””清理空目录””” print(f”{‘预览’ if dry_run else ‘执行’}空目录清理”) print(“=” * 60) cleaned_dirs = 0 for rule in self.cleanup_rules: for path in rule[‘paths’]: if not path or not os.path.exists(path): continue try: for root, dirs, files in os.walk(path, topdown=False): # 检查目录是否为空 if not os.listdir(root): if dry_run: print(f” 将删除空目录: {root}”) else: try: os.rmdir(root) print(f” 已删除空目录: {root}”) cleaned_dirs += 1 except Exception as e: error_msg = f”删除目录 {root} 失败: {e}” print(f” 错误: {error_msg}”) self.errors.append(error_msg) except Exception as e: self.errors.append(f”遍历目录 {path} 时出错: {e}”) if not dry_run: print(f”空目录清理完成: {cleaned_dirs} 个目录”) return cleaned_dirs def generate_report(self): “””生成清理报告””” report = [] report.append(“=” * 80) report.append(“系统清理报告”) report.append(“=” * 80) report.append(f”清理时间: {datetime.now().strftime(‘%Y-%m-%d %H:%M:%S’)}”) report.append(f”操作系统: {self.os_type}”) report.append(“”) # 清理统计 report.append(“清理统计:”) report.append(f” 删除文件: {len(self.cleaned_files)} 个”) report.append(f” 释放空间: {self.format_bytes(self.cleaned_size)}”) report.append(“”) # 清理的文件列表 if self.cleaned_files: report.append(“已清理的文件:”) report.append(“-” * 50) for filepath in self.cleaned_files: report.append(f” {filepath}”) report.append(“”) # 错误信息 if self.errors: report.append(“错误信息:”) report.append(“-” * 50) for error in self.errors[:20]: # 只显示前20个错误 report.append(f” {error}”) if len(self.errors) > 20: report.append(f” … 还有 {len(self.errors) – 20} 个错误”) report.append(“”) report.append(“=” * 80) return “n”.join(report) def save_report(self, filename): “””保存报告到文件””” try: report = self.generate_report() with open(filename, ‘w’, encoding=’utf-8′) as f: f.write(report) print(f”报告已保存到: {filename}”) return True except Exception as e: print(f”保存报告时出错: {e}”) return False def create_sample_config(): “””创建示例配置文件””” config = { “cleanup_rules”: [ { “name”: “自定义临时文件”, “paths”: [“/custom/temp/path”], “patterns”: [“*.tmp”, “*.temp”], “age_days”: 7 } ], “whitelist”: [ “/important/files/not/to/delete” ] } try: with open(‘cleaner_config.json’, ‘w’, encoding=’utf-8′) as f: json.dump(config, f, indent=2, ensure_ascii=False) print(“示例配置文件已创建: cleaner_config.json”) return True except Exception as e: print(f”创建示例配置文件时出错: {e}”) return False def main(): parser = argparse.ArgumentParser(description=”系统清理工具”) parser.add_argument(“-c”, “–config”, help=”配置文件路径”) parser.add_argument(“-p”, “–preview”, action=”store_true”, help=”预览模式,不实际删除文件”) parser.add_argument(“-o”, “–output”, help=”保存报告到文件”) parser.add_argument(“–create-config”, action=”store_true”, help=”创建示例配置文件”) parser.add_argument(“–clean-empty-dirs”, action=”store_true”, help=”清理空目录”) parser.add_argument(“–add-whitelist”, action=”append”, help=”添加白名单路径”) args = parser.parse_args() # 创建示例配置文件 if args.create_config: create_sample_config() return try: cleaner = SystemCleaner() # 加载配置文件 if args.config: if not cleaner.load_config(args.config): print(“加载配置文件失败”) sys.exit(1) # 添加白名单 if args.add_whitelist: cleaner.add_whitelist(args.add_whitelist) # 预览或执行清理 if args.preview: cleaner.preview_cleanup() else: # 执行清理 cleaned_count, cleaned_size = cleaner.perform_cleanup(dry_run=False) # 清理空目录 if args.clean_empty_dirs: cleaner.clean_empty_dirs(dry_run=False) # 生成报告 if args.output: cleaner.save_report(args.output) else: print(cleaner.generate_report()) except KeyboardInterrupt: print(“nn用户中断操作”) except Exception as e: print(f”程序执行出错: {e}”) sys.exit(1) if __name__ == “__main__”: main()
  • 这个系统清理工具提供了一个安全、灵活的系统清理解决方案,能够跨平台清理各种类型的垃圾文件。它具有预览模式、白名单保护、自定义规则等安全特性,可以有效防止误删重要文件。工具支持配置文件管理,便于定制清理规则,适用于日常系统维护、存储空间优化和性能提升等多种场景。通过定期使用这个工具,用户可以保持系统的清洁和高效运行。 以上就是Python实现安全清理各种系统垃圾文件的详细内容,更多关于Python清理系统的资料请关注风君子博客其它相关文章! 您可能感兴趣的文章: 使用Python实现Windows系统垃圾清理 Python办公自动化之自动化清理数据和自动化系统命令详解 用Python自动清理系统垃圾的实现 如何批量清理系统临时文件(语言:C#、 C/C++、 php 、python 、java )
  • 目录
    • 简介
    • 功能介绍
    • 应用场景
    • 报错处理
    • 代码实现
    • 使用方法
      • 基本使用
      • 配置文件示例
      • 命令行参数说明
      • 使用示例
    • 总结

      随着时间的推移,计算机会积累大量的临时文件、缓存文件、日志文件和其他不必要的数据,这些文件不仅占用宝贵的存储空间,还可能影响系统的性能。定期清理这些无用文件是系统维护的重要环节。本文将介绍一个实用的Python脚本——系统清理工具,它可以安全地清理各种系统垃圾文件,帮助用户释放存储空间并提升系统性能。

      这个系统清理工具具有以下核心功能:

      • 多类型文件清理:支持清理临时文件、缓存文件、日志文件、回收站等
      • 跨平台支持:支持Windows、Linux和macOS操作系统
      • 安全清理机制:提供预览模式,避免误删重要文件
      • 自定义清理规则:支持自定义要清理的文件类型和目录
      • 磁盘空间统计:显示清理前后磁盘空间的变化
      • 日志记录:记录清理操作的详细信息
      • 定时任务支持:可以集成到定时任务中定期清理系统
      • 白名单保护:支持设置白名单,保护重要文件不被误删

      这个工具适用于以下场景:

      • 日常系统维护:定期清理系统垃圾文件
      • 存储空间优化:释放磁盘空间,特别是存储空间紧张时
      • 性能优化:清理过多的临时文件以提升系统性能
      • 系统准备:在系统迁移或重装前清理无用文件
      • 故障排查:清理可能引起问题的缓存文件
      • 隐私保护:清理浏览历史、临时文件等隐私相关数据

      脚本包含了完善的错误处理机制:

      • 权限验证:检查是否有足够的权限访问和删除文件
      • 路径安全性检查:验证要清理的路径是否安全,防止误删系统关键文件
      • 文件锁定处理:处理被其他程序占用的文件
      • 磁盘空间检查:在操作前检查是否有足够的磁盘空间
      • 异常捕获:捕获并处理运行过程中可能出现的各种异常
      • 回滚机制:在必要时提供操作回滚功能

      import os
      import sys
      import argparse
      import json
      import shutil
      import tempfile
      from datetime import datetime, timedelta
      import platform
      import glob
      
      class SystemCleaner:
          def __init__(self):
              self.os_type = platform.system().lower()
              self.cleanup_rules = []
              self.whitelist = set()
              self.cleaned_files = []
              self.cleaned_size = 0
              self.errors = []
              
              # 默认清理规则
              self._set_default_rules()
              
          def _set_default_rules(self):
              """设置默认清理规则"""
              if self.os_type == 'windows':
                  # Windows系统默认清理规则
                  self.cleanup_rules.extend([
                      {
                          'name': '临时文件',
                          'paths': [
                              os.environ.get('TEMP', ''),
                              os.path.join(os.environ.get('SYSTEMROOT', ''), 'Temp'),
                              os.path.expanduser('~\AppData\Local\Temp')
                          ],
                          'patterns': ['*'],
                          'age_days': 7
                      },
                      {
                          'name': '回收站',
                          'paths': [os.path.join(drive + ':\', '$Recycle.Bin') for drive in 'CDEFGHIJKLMNOPQRSTUVWXYZ'],
                          'patterns': ['*'],
                          'age_days': 30
                      },
                      {
                          'name': '浏览器缓存',
                          'paths': [
                              os.path.expanduser('~\AppData\Local\Google\Chrome\User Data\Default\Cache'),
                              os.path.expanduser('~\AppData\Local\Mozilla\Firefox\Profiles\*\cache2'),
                              os.path.expanduser('~\AppData\Local\Microsoft\Edge\User Data\Default\Cache')
                          ],
                          'patterns': ['*'],
                          'age_days': 7
                      }
                  ])
              elif self.os_type == 'linux':
                  # Linux系统默认清理规则
                  self.cleanup_rules.extend([
                      {
                          'name': '临时文件',
                          'paths': ['/tmp', '/var/tmp'],
                          'patterns': ['*'],
                          'age_days': 7
                      },
                      {
                          'name': '用户缓存',
                          'paths': [os.path.expanduser('~/.cache')],
                          'patterns': ['*'],
                          'age_days': 30
                      },
                      {
                          'name': '日志文件',
                          'paths': ['/var/log'],
                          'patterns': ['*.log.*', '*.gz'],
                          'age_days': 30
                      }
                  ])
              elif self.os_type == 'darwin':  # macOS
                  # macOS系统默认清理规则
                  self.cleanup_rules.extend([
                      {
                          'name': '临时文件',
                          'paths': ['/tmp', '/var/tmp'],
                          'patterns': ['*'],
                          'age_days': 7
                      },
                      {
                          'name': '用户缓存',
                          'paths': [os.path.expanduser('~/Library/Caches')],
                          'patterns': ['*'],
                          'age_days': 30
                      },
                      {
                          'name': '日志文件',
                          'paths': [os.path.expanduser('~/Library/Logs')],
                          'patterns': ['*.log.*'],
                          'age_days': 30
                      }
                  ])
                  
          def add_whitelist(self, paths):
              """添加白名单路径"""
              if isinstance(paths, str):
                  paths = [paths]
              for path in paths:
                  self.whitelist.add(os.path.abspath(path))
                  
          def load_config(self, config_file):
              """从配置文件加载清理规则"""
              try:
                  with open(config_file, 'r', encoding='utf-8') as f:
                      config = json.load(f)
                      
                  # 加载清理规则
                  if 'cleanup_rules' in config:
                      self.cleanup_rules = config['cleanup_rules']
                      
                  # 加载白名单
                  if 'whitelist' in config:
                      self.add_whitelist(config['whitelist'])
                      
                  return True
              except Exception as e:
                  self.errors.append(f"加载配置文件失败: {e}")
                  return False
                  
          def save_config(self, config_file):
              """保存配置到文件"""
              try:
                  config = {
                      'cleanup_rules': self.cleanup_rules,
                      'whitelist': list(self.whitelist)
                  }
                  
                  with open(config_file, 'w', encoding='utf-8') as f:
                      json.dump(config, f, indent=2, ensure_ascii=False)
                      
                  return True
              except Exception as e:
                  self.errors.append(f"保存配置文件失败: {e}")
                  return False
                  
          def format_bytes(self, bytes_value):
              """格式化字节单位"""
              for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
                  if bytes_value < 1024.0:
                      return f"{bytes_value:.2f} {unit}"
                  bytes_value /= 1024.0
              return f"{bytes_value:.2f} PB"
              
          def is_safe_path(self, path):
              """检查路径是否安全"""
              # 检查是否在白名单中
              abs_path = os.path.abspath(path)
              for whitelist_path in self.whitelist:
                  if abs_path.startswith(whitelist_path):
                      return False
                      
              # 检查是否是系统关键目录
              critical_paths = []
              if self.os_type == 'windows':
                  system_root = os.environ.get('SYSTEMROOT', 'C:\Windows')
                  critical_paths = [system_root, 'C:\Program Files', 'C:\Program Files (x86)']
              elif self.os_type in ['linux', 'darwin']:
                  critical_paths = ['/bin', '/sbin', '/usr/bin', '/usr/sbin', '/etc', '/boot']
                  
              for critical_path in critical_paths:
                  if abs_path.startswith(critical_path):
                      return False
                      
              return True
              
          def get_file_age(self, filepath):
              """获取文件年龄(天数)"""
              try:
                  file_time = os.path.getmtime(filepath)
                  file_datetime = datetime.fromtimestamp(file_time)
                  age = datetime.now() - file_datetime
                  return age.days
              except:
                  return 0
                  
          def match_patterns(self, filename, patterns):
              """检查文件名是否匹配模式"""
              for pattern in patterns:
                  if glob.fnmatch.fnmatch(filename, pattern):
                      return True
              return False
              
          def scan_files(self, rule):
              """扫描符合规则的文件"""
              found_files = []
              
              for path in rule['paths']:
                  if not path or not os.path.exists(path):
                      continue
                      
                  try:
                      # 递归遍历目录
                      for root, dirs, files in os.walk(path):
                          # 跳过隐藏目录
                          dirs[:] = [d for d in dirs if not d.startswith('.')]
                          
                          for filename in files:
                              # 跳过隐藏文件
                              if filename.startswith('.'):
                                  continue
                                  
                              filepath = os.path.join(root, filename)
                              
                              # 检查文件是否匹配模式
                              if not self.match_patterns(filename, rule['patterns']):
                                  continue
                                  
                              # 检查文件年龄
                              if 'age_days' in rule:
                                  file_age = self.get_file_age(filepath)
                                  if file_age < rule['age_days']:
                                      continue
                                      
                              # 检查路径安全性
                              if not self.is_safe_path(filepath):
                                  continue
                                  
                              # 获取文件大小
                              try:
                                  file_size = os.path.getsize(filepath)
                              except:
                                  file_size = 0
                                  
                              found_files.append({
                                  'path': filepath,
                                  'size': file_size,
                                  'age': self.get_file_age(filepath)
                              })
                              
                  except Exception as e:
                      self.errors.append(f"扫描目录 {path} 时出错: {e}")
                      
              return found_files
              
          def preview_cleanup(self):
              """预览清理操作"""
              print("系统清理预览")
              print("=" * 60)
              print(f"操作系统: {self.os_type}")
              print()
              
              total_files = 0
              total_size = 0
              
              for rule in self.cleanup_rules:
                  print(f"清理规则: {rule['name']}")
                  files = self.scan_files(rule)
                  
                  if files:
                      rule_size = sum(f['size'] for f in files)
                      print(f"  发现文件: {len(files)} 个")
                      print(f"  预计释放: {self.format_bytes(rule_size)}")
                      total_files += len(files)
                      total_size += rule_size
                      
                      # 显示前10个文件作为示例
                      print("  文件示例:")
                      for i, file_info in enumerate(files[:10]):
                          print(f"    {file_info['path']} ({self.format_bytes(file_info['size'])}, {file_info['age']}天)")
                      if len(files) > 10:
                          print(f"    ... 还有 {len(files) - 10} 个文件")
                  else:
                      print("  未发现符合条件的文件")
                  print()
                  
              print(f"总计:")
              print(f"  文件数量: {total_files}")
              print(f"  预计释放: {self.format_bytes(total_size)}")
              
              return total_files, total_size
              
          def perform_cleanup(self, dry_run=True):
              """执行清理操作"""
              print(f"{'预览' if dry_run else '执行'}系统清理")
              print("=" * 60)
              
              self.cleaned_files = []
              self.cleaned_size = 0
              cleaned_count = 0
              
              for rule in self.cleanup_rules:
                  print(f"处理规则: {rule['name']}")
                  files = self.scan_files(rule)
                  
                  for file_info in files:
                      filepath = file_info['path']
                      filesize = file_info['size']
                      
                      if dry_run:
                          print(f"  将删除: {filepath} ({self.format_bytes(filesize)})")
                      else:
                          try:
                              os.remove(filepath)
                              print(f"  已删除: {filepath}")
                              self.cleaned_files.append(filepath)
                              self.cleaned_size += filesize
                              cleaned_count += 1
                          except Exception as e:
                              error_msg = f"删除文件 {filepath} 失败: {e}"
                              print(f"  错误: {error_msg}")
                              self.errors.append(error_msg)
                              
                  print()
                  
              if not dry_run:
                  print(f"清理完成:")
                  print(f"  删除文件: {cleaned_count} 个")
                  print(f"  释放空间: {self.format_bytes(self.cleaned_size)}")
                  
              return cleaned_count, self.cleaned_size
              
          def clean_empty_dirs(self, dry_run=True):
              """清理空目录"""
              print(f"{'预览' if dry_run else '执行'}空目录清理")
              print("=" * 60)
              
              cleaned_dirs = 0
              
              for rule in self.cleanup_rules:
                  for path in rule['paths']:
                      if not path or not os.path.exists(path):
                          continue
                          
                      try:
                          for root, dirs, files in os.walk(path, topdown=False):
                              # 检查目录是否为空
                              if not os.listdir(root):
                                  if dry_run:
                                      print(f"  将删除空目录: {root}")
                                  else:
                                      try:
                                          os.rmdir(root)
                                          print(f"  已删除空目录: {root}")
                                          cleaned_dirs += 1
                                      except Exception as e:
                                          error_msg = f"删除目录 {root} 失败: {e}"
                                          print(f"  错误: {error_msg}")
                                          self.errors.append(error_msg)
                      except Exception as e:
                          self.errors.append(f"遍历目录 {path} 时出错: {e}")
                          
              if not dry_run:
                  print(f"空目录清理完成: {cleaned_dirs} 个目录")
                  
              return cleaned_dirs
              
          def generate_report(self):
              """生成清理报告"""
              report = []
              report.append("=" * 80)
              report.append("系统清理报告")
              report.append("=" * 80)
              report.append(f"清理时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
              report.append(f"操作系统: {self.os_type}")
              report.append("")
              
              # 清理统计
              report.append("清理统计:")
              report.append(f"  删除文件: {len(self.cleaned_files)} 个")
              report.append(f"  释放空间: {self.format_bytes(self.cleaned_size)}")
              report.append("")
              
              # 清理的文件列表
              if self.cleaned_files:
                  report.append("已清理的文件:")
                  report.append("-" * 50)
                  for filepath in self.cleaned_files:
                      report.append(f"  {filepath}")
                  report.append("")
                  
              # 错误信息
              if self.errors:
                  report.append("错误信息:")
                  report.append("-" * 50)
                  for error in self.errors[:20]:  # 只显示前20个错误
                      report.append(f"  {error}")
                  if len(self.errors) > 20:
                      report.append(f"  ... 还有 {len(self.errors) - 20} 个错误")
                  report.append("")
                  
              report.append("=" * 80)
              return "n".join(report)
              
          def save_report(self, filename):
              """保存报告到文件"""
              try:
                  report = self.generate_report()
                  with open(filename, 'w', encoding='utf-8') as f:
                      f.write(report)
                  print(f"报告已保存到: {filename}")
                  return True
              except Exception as e:
                  print(f"保存报告时出错: {e}")
                  return False
      
      def create_sample_config():
          """创建示例配置文件"""
          config = {
              "cleanup_rules": [
                  {
                      "name": "自定义临时文件",
                      "paths": ["/custom/temp/path"],
                      "patterns": ["*.tmp", "*.temp"],
                      "age_days": 7
                  }
              ],
              "whitelist": [
                  "/important/files/not/to/delete"
              ]
          }
          
          try:
              with open('cleaner_config.json', 'w', encoding='utf-8') as f:
                  json.dump(config, f, indent=2, ensure_ascii=False)
              print("示例配置文件已创建: cleaner_config.json")
              return True
          except Exception as e:
              print(f"创建示例配置文件时出错: {e}")
              return False
      
      def main():
          parser = argparse.ArgumentParser(description="系统清理工具")
          parser.add_argument("-c", "--config", help="配置文件路径")
          parser.add_argument("-p", "--preview", action="store_true", help="预览模式,不实际删除文件")
          parser.add_argument("-o", "--output", help="保存报告到文件")
          parser.add_argument("--create-config", action="store_true", help="创建示例配置文件")
          parser.add_argument("--clean-empty-dirs", action="store_true", help="清理空目录")
          parser.add_argument("--add-whitelist", action="append", help="添加白名单路径")
          
          args = parser.parse_args()
          
          # 创建示例配置文件
          if args.create_config:
              create_sample_config()
              return
              
          try:
              cleaner = SystemCleaner()
              
              # 加载配置文件
              if args.config:
                  if not cleaner.load_config(args.config):
                      print("加载配置文件失败")
                      sys.exit(1)
                      
              # 添加白名单
              if args.add_whitelist:
                  cleaner.add_whitelist(args.add_whitelist)
                  
              # 预览或执行清理
              if args.preview:
                  cleaner.preview_cleanup()
              else:
                  # 执行清理
                  cleaned_count, cleaned_size = cleaner.perform_cleanup(dry_run=False)
                  
                  # 清理空目录
                  if args.clean_empty_dirs:
                      cleaner.clean_empty_dirs(dry_run=False)
                      
                  # 生成报告
                  if args.output:
                      cleaner.save_report(args.output)
                  else:
                      print(cleaner.generate_report())
                      
          except KeyboardInterrupt:
              print("nn用户中断操作")
          except Exception as e:
              print(f"程序执行出错: {e}")
              sys.exit(1)
      
      if __name__ == "__main__":
          main()
      

      # 创建示例配置文件
      python system_cleaner.py --create-config
      
      # 预览清理操作(不实际删除文件)
      python system_cleaner.py --preview
      
      # 执行清理操作
      python system_cleaner.py
      
      # 使用配置文件
      python system_cleaner.py -c cleaner_config.json
      
      # 保存清理报告
      python system_cleaner.py -o cleanup_report.txt
      
      # 清理空目录
      python system_cleaner.py --clean-empty-dirs
      
      # 添加白名单路径
      python system_cleaner.py --add-whitelist /important/data --preview
      

      创建的示例配置文件 cleaner_config.json 内容如下:

      {
        "cleanup_rules": [
          {
            "name": "自定义临时文件",
            "paths": ["/custom/temp/path"],
            "patterns": ["*.tmp", "*.temp"],
            "age_days": 7
          }
        ],
        "whitelist": [
          "/important/files/not/to/delete"
        ]
      }
      

      • -c, --config: 配置文件路径
      • -p, --preview: 预览模式,不实际删除文件
      • -o, --output: 保存报告到指定文件
      • --create-config: 创建示例配置文件
      • --clean-empty-dirs: 清理空目录
      • --add-whitelist: 添加白名单路径(可多次使用)

      预览清理操作

      python system_cleaner.py --preview
      

      执行清理并保存报告

      python system_cleaner.py -o cleanup_$(date +%Y%m%d).txt
      

      使用自定义配置

      python system_cleaner.py -c my_cleaner_config.json --preview
      

      添加白名单并清理

      python system_cleaner.py --add-whitelist /home/user/important --clean-empty-dirs
      

      这个系统清理工具提供了一个安全、灵活的系统清理解决方案,能够跨平台清理各种类型的垃圾文件。它具有预览模式、白名单保护、自定义规则等安全特性,可以有效防止误删重要文件。工具支持配置文件管理,便于定制清理规则,适用于日常系统维护、存储空间优化和性能提升等多种场景。通过定期使用这个工具,用户可以保持系统的清洁和高效运行。

      以上就是Python实现安全清理各种系统垃圾文件的详细内容,更多关于Python清理系统的资料请关注风君子博客其它相关文章!

      您可能感兴趣的文章:

      • 使用Python实现Windows系统垃圾清理
      • Python办公自动化之自动化清理数据和自动化系统命令详解
      • 用Python自动清理系统垃圾的实现
      • 如何批量清理系统临时文件(语言:C#、 C/C++、 php 、python 、java )

      站内搜索