| import os
|
| import shutil
|
| from pathlib import Path
|
|
|
|
|
|
|
| ROOT_DIR = Path("./src/app")
|
|
|
| EXCLUDE_DIRS = [
|
| Path("./dist"),
|
| Path("./venv"),
|
| Path("./.git"),
|
| ]
|
|
|
|
|
| def is_excluded(path: Path) -> bool:
|
| """判断路径是否在排除目录中"""
|
| for exclude_dir in EXCLUDE_DIRS:
|
|
|
| abs_exclude = exclude_dir.absolute()
|
| abs_path = path.absolute()
|
| if abs_path.is_relative_to(abs_exclude):
|
| return True
|
| return False
|
|
|
| def clean_pyc_and_cache():
|
| """递归删除.pyc文件和__pycache__目录"""
|
| pyc_count = 0
|
| cache_count = 0
|
|
|
|
|
| for root in ROOT_DIR.rglob("*"):
|
|
|
| if is_excluded(root):
|
| continue
|
|
|
|
|
| if root.is_dir() and root.name == "__pycache__":
|
| try:
|
| shutil.rmtree(root, ignore_errors=True)
|
| cache_count += 1
|
| print(f"🗑️ 删除__pycache__目录:{root.absolute()}")
|
| except Exception as e:
|
| print(f"⚠️ 无法删除__pycache__目录:{root.absolute()} → 错误:{str(e)}")
|
|
|
|
|
| elif root.is_file() and root.suffix == ".pyc":
|
| try:
|
| root.unlink()
|
| pyc_count += 1
|
|
|
|
|
| except Exception as e:
|
| print(f"⚠️ 无法删除.pyc文件:{root.absolute()} → 错误:{str(e)}")
|
|
|
|
|
| print(f"\n===== 清理完成!=====")
|
| print(f"✅ 共删除 {pyc_count} 个.pyc文件")
|
| print(f"✅ 共删除 {cache_count} 个__pycache__目录")
|
|
|
| if __name__ == "__main__":
|
| print(f"===== 开始清理项目中的.pyc文件和__pycache__目录 =====\n🔍 根目录:{ROOT_DIR.absolute()}\n🔍 排除目录:{[d.absolute() for d in EXCLUDE_DIRS]}")
|
| clean_pyc_and_cache() |