cache_manager.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 缓存管理工具
  5. 用于管理视频识别过程中的临时缓存文件
  6. """
  7. import os
  8. import time
  9. import argparse
  10. from pathlib import Path
  11. # 缓存目录配置
  12. CACHE_DIR = os.path.join(os.path.dirname(__file__), 'cache')
  13. CACHE_MAX_AGE = 3600 # 1小时
  14. def get_cache_info():
  15. """获取缓存信息"""
  16. if not os.path.exists(CACHE_DIR):
  17. return {
  18. 'exists': False,
  19. 'total_files': 0,
  20. 'total_size_mb': 0,
  21. 'oldest_file': None,
  22. 'newest_file': None
  23. }
  24. files = []
  25. total_size = 0
  26. for filename in os.listdir(CACHE_DIR):
  27. file_path = os.path.join(CACHE_DIR, filename)
  28. if os.path.isfile(file_path):
  29. stat = os.stat(file_path)
  30. files.append({
  31. 'name': filename,
  32. 'size': stat.st_size,
  33. 'mtime': stat.st_mtime,
  34. 'age': time.time() - stat.st_mtime
  35. })
  36. total_size += stat.st_size
  37. if not files:
  38. return {
  39. 'exists': True,
  40. 'total_files': 0,
  41. 'total_size_mb': 0,
  42. 'oldest_file': None,
  43. 'newest_file': None
  44. }
  45. # 按修改时间排序
  46. files.sort(key=lambda x: x['mtime'])
  47. return {
  48. 'exists': True,
  49. 'total_files': len(files),
  50. 'total_size_mb': total_size / (1024 * 1024),
  51. 'oldest_file': {
  52. 'name': files[0]['name'],
  53. 'age_hours': files[0]['age'] / 3600
  54. },
  55. 'newest_file': {
  56. 'name': files[-1]['name'],
  57. 'age_hours': files[-1]['age'] / 3600
  58. }
  59. }
  60. def cleanup_cache(force=False, dry_run=False):
  61. """清理缓存文件"""
  62. if not os.path.exists(CACHE_DIR):
  63. print("缓存目录不存在")
  64. return 0
  65. current_time = time.time()
  66. cleaned_count = 0
  67. cleaned_size = 0
  68. for filename in os.listdir(CACHE_DIR):
  69. file_path = os.path.join(CACHE_DIR, filename)
  70. if os.path.isfile(file_path):
  71. file_age = current_time - os.path.getmtime(file_path)
  72. should_clean = force or file_age > CACHE_MAX_AGE
  73. if should_clean:
  74. file_size = os.path.getsize(file_path)
  75. if dry_run:
  76. print(f"将要清理: {filename} (大小: {file_size/1024:.1f}KB, 年龄: {file_age/3600:.1f}小时)")
  77. else:
  78. try:
  79. os.remove(file_path)
  80. cleaned_count += 1
  81. cleaned_size += file_size
  82. print(f"已清理: {filename}")
  83. except Exception as e:
  84. print(f"清理失败: {filename}, 错误: {e}")
  85. if not dry_run:
  86. print(f"清理完成: {cleaned_count} 个文件, 释放空间: {cleaned_size/(1024*1024):.2f}MB")
  87. return cleaned_count
  88. def show_cache_status():
  89. """显示缓存状态"""
  90. info = get_cache_info()
  91. print("=" * 50)
  92. print("缓存状态信息")
  93. print("=" * 50)
  94. if not info['exists']:
  95. print("缓存目录不存在")
  96. return
  97. print(f"缓存目录: {CACHE_DIR}")
  98. print(f"文件数量: {info['total_files']}")
  99. print(f"总大小: {info['total_size_mb']:.2f} MB")
  100. if info['oldest_file']:
  101. print(f"最旧文件: {info['oldest_file']['name']} ({info['oldest_file']['age_hours']:.1f}小时前)")
  102. if info['newest_file']:
  103. print(f"最新文件: {info['newest_file']['name']} ({info['newest_file']['age_hours']:.1f}小时前)")
  104. # 显示文件列表
  105. if info['total_files'] > 0:
  106. print("\n文件列表:")
  107. print("-" * 50)
  108. if os.path.exists(CACHE_DIR):
  109. for filename in sorted(os.listdir(CACHE_DIR)):
  110. file_path = os.path.join(CACHE_DIR, filename)
  111. if os.path.isfile(file_path):
  112. stat = os.stat(file_path)
  113. age = time.time() - stat.st_mtime
  114. size = stat.st_size
  115. print(f"{filename:<30} {size/1024:>8.1f}KB {age/3600:>6.1f}小时前")
  116. def main():
  117. """主函数"""
  118. parser = argparse.ArgumentParser(description='缓存管理工具')
  119. parser.add_argument('action', choices=['status', 'clean', 'cleanup'],
  120. help='操作类型: status(查看状态), clean(清理), cleanup(清理)')
  121. parser.add_argument('--force', '-f', action='store_true',
  122. help='强制清理所有文件(不检查年龄)')
  123. parser.add_argument('--dry-run', '-n', action='store_true',
  124. help='试运行模式,不实际删除文件')
  125. args = parser.parse_args()
  126. if args.action == 'status':
  127. show_cache_status()
  128. elif args.action in ['clean', 'cleanup']:
  129. if args.dry_run:
  130. print("试运行模式 - 不会实际删除文件")
  131. cleanup_cache(force=args.force, dry_run=True)
  132. else:
  133. print("开始清理缓存...")
  134. cleaned = cleanup_cache(force=args.force, dry_run=False)
  135. if cleaned > 0:
  136. print(f"清理完成,共清理 {cleaned} 个文件")
  137. else:
  138. print("没有需要清理的文件")
  139. if __name__ == '__main__':
  140. main()