#!/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)