Spaces:
Running
Running
File size: 6,665 Bytes
b8277c4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | #!/usr/bin/env python3
"""
π§Ή PYTHON CACHE CLEANER
Removes all __pycache__ folders and .pyc files from the backend directory
"""
import os
import shutil
import sys
from pathlib import Path
from typing import List, Tuple
def find_pycache_dirs(root_dir: str) -> List[str]:
"""Find all __pycache__ directories recursively"""
pycache_dirs = []
for root, dirs, files in os.walk(root_dir):
if '__pycache__' in dirs:
pycache_path = os.path.join(root, '__pycache__')
pycache_dirs.append(pycache_path)
return pycache_dirs
def find_pyc_files(root_dir: str) -> List[str]:
"""Find all .pyc files recursively"""
pyc_files = []
for root, dirs, files in os.walk(root_dir):
for file in files:
if file.endswith('.pyc'):
pyc_path = os.path.join(root, file)
pyc_files.append(pyc_path)
return pyc_files
def delete_pycache_dirs(pycache_dirs: List[str]) -> Tuple[int, List[str]]:
"""Delete __pycache__ directories and return count and any errors"""
deleted_count = 0
errors = []
for pycache_dir in pycache_dirs:
try:
shutil.rmtree(pycache_dir)
print(f"β
Deleted: {pycache_dir}")
deleted_count += 1
except Exception as e:
error_msg = f"β Failed to delete {pycache_dir}: {str(e)}"
print(error_msg)
errors.append(error_msg)
return deleted_count, errors
def delete_pyc_files(pyc_files: List[str]) -> Tuple[int, List[str]]:
"""Delete .pyc files and return count and any errors"""
deleted_count = 0
errors = []
for pyc_file in pyc_files:
try:
os.remove(pyc_file)
print(f"β
Deleted: {pyc_file}")
deleted_count += 1
except Exception as e:
error_msg = f"β Failed to delete {pyc_file}: {str(e)}"
print(error_msg)
errors.append(error_msg)
return deleted_count, errors
def get_directory_size(root_dir: str) -> int:
"""Calculate total size of __pycache__ directories in bytes"""
total_size = 0
for root, dirs, files in os.walk(root_dir):
if '__pycache__' in dirs:
pycache_path = os.path.join(root, '__pycache__')
try:
for dirpath, dirnames, filenames in os.walk(pycache_path):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
try:
total_size += os.path.getsize(filepath)
except (OSError, FileNotFoundError):
pass
except (OSError, FileNotFoundError):
pass
return total_size
def format_size(size_bytes: int) -> str:
"""Format size in human readable format"""
if size_bytes == 0:
return "0 B"
size_names = ["B", "KB", "MB", "GB"]
i = 0
size = float(size_bytes)
while size >= 1024.0 and i < len(size_names) - 1:
size /= 1024.0
i += 1
return f"{size:.1f} {size_names[i]}"
def main():
"""Main function to clean Python cache files"""
print("π§Ή PYTHON CACHE CLEANER")
print("=" * 50)
# Get the backend directory (current script's directory)
backend_dir = os.path.dirname(os.path.abspath(__file__))
print(f"π Scanning directory: {backend_dir}")
# Calculate cache size before deletion
print("\nπ Analyzing cache files...")
cache_size = get_directory_size(backend_dir)
print(f"πΎ Total cache size: {format_size(cache_size)}")
# Find all cache files and directories
pycache_dirs = find_pycache_dirs(backend_dir)
pyc_files = find_pyc_files(backend_dir)
print(f"\nπ Found:")
print(f" π __pycache__ directories: {len(pycache_dirs)}")
print(f" π .pyc files: {len(pyc_files)}")
if len(pycache_dirs) == 0 and len(pyc_files) == 0:
print("\n⨠No cache files found! Directory is already clean.")
return
# Show what will be deleted
print(f"\nπ Cache directories to delete:")
for pycache_dir in pycache_dirs:
rel_path = os.path.relpath(pycache_dir, backend_dir)
print(f" ποΈ {rel_path}")
if pyc_files:
print(f"\nπ .pyc files to delete:")
for pyc_file in pyc_files[:10]: # Show first 10
rel_path = os.path.relpath(pyc_file, backend_dir)
print(f" π {rel_path}")
if len(pyc_files) > 10:
print(f" ... and {len(pyc_files) - 10} more")
# Ask for confirmation
print(f"\nβ οΈ This will permanently delete {len(pycache_dirs)} directories and {len(pyc_files)} files")
print(f"πΎ Total space to be freed: {format_size(cache_size)}")
try:
confirm = input("\nπ€ Proceed with deletion? (y/N): ").strip().lower()
if confirm not in ['y', 'yes']:
print("β Operation cancelled by user")
return
except KeyboardInterrupt:
print("\nβ Operation cancelled by user")
return
print(f"\nπ§Ή Starting cleanup...")
# Delete __pycache__ directories
dirs_deleted, dir_errors = delete_pycache_dirs(pycache_dirs)
# Delete .pyc files
files_deleted, file_errors = delete_pyc_files(pyc_files)
# Summary
print(f"\nπ CLEANUP SUMMARY")
print("=" * 30)
print(f"β
Directories deleted: {dirs_deleted}/{len(pycache_dirs)}")
print(f"β
Files deleted: {files_deleted}/{len(pyc_files)}")
print(f"πΎ Space freed: {format_size(cache_size)}")
if dir_errors or file_errors:
print(f"\nβ οΈ ERRORS ENCOUNTERED:")
for error in dir_errors + file_errors:
print(f" {error}")
print(f"\nβ {len(dir_errors + file_errors)} errors occurred during cleanup")
else:
print(f"\nπ Cleanup completed successfully!")
# Final verification
remaining_pycache = find_pycache_dirs(backend_dir)
remaining_pyc = find_pyc_files(backend_dir)
if remaining_pycache or remaining_pyc:
print(f"\nβ οΈ Warning: {len(remaining_pycache)} __pycache__ dirs and {len(remaining_pyc)} .pyc files still remain")
else:
print(f"\n⨠All Python cache files have been successfully removed!")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n\nβ Cleanup interrupted by user")
sys.exit(1)
except Exception as e:
print(f"\n\nπ₯ Unexpected error: {str(e)}")
sys.exit(1) |