clean.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import os
  2. import shutil
  3. from pathlib import Path
  4. PROJECT_ROOT = os.path.join(os.path.abspath(__file__),os.pardir,os.pardir)
  5. def clean_python_cache():
  6. """
  7. 清理Python缓存文件和目录
  8. - __pycache__ 目录
  9. - .pyc 文件
  10. - .pyo 文件
  11. - .pyd 文件
  12. """
  13. # 转换为Path对象
  14. base_path = Path(PROJECT_ROOT)
  15. # 要清理的文件类型
  16. cache_patterns = [
  17. "**/__pycache__",
  18. "**/*.pyc",
  19. # "**/*.pyo",
  20. # "**/*.pyd"
  21. ]
  22. total_removed = 0
  23. for pattern in cache_patterns:
  24. for path in base_path.glob(pattern):
  25. try:
  26. if path.is_dir():
  27. shutil.rmtree(path)
  28. print(f"Removed directory: {path}")
  29. else:
  30. path.unlink()
  31. print(f"Removed file: {path}")
  32. total_removed += 1
  33. except Exception as e:
  34. print(f"Error removing {path}: {e}")
  35. print(f"\nTotal items removed: {total_removed}")
  36. if __name__ == "__main__":
  37. clean_python_cache()