#!/usr/bin/env python3 """Поиск старых скриншотов в типовых папках.""" from __future__ import annotations import argparse import os import time from pathlib import Path MARKERS = ("screenshot", "screen shot", "screen_shot", "снимок экрана", "snip") EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".heic"} def default_roots() -> list[Path]: home = Path.home() candidates = [home / "Pictures", home / "Desktop"] return [path for path in candidates if path.is_dir()] def looks_like_screenshot(name: str) -> bool: lowered = name.lower() return any(marker in lowered for marker in MARKERS) def main() -> int: parser = argparse.ArgumentParser(description="Старые скриншоты") parser.add_argument("--path", type=Path, action="append", default=[], help="Дополнительная папка") parser.add_argument("--days", type=int, default=180, help="Минимальный возраст в днях") parser.add_argument("--apply", action="store_true", help="Удалить найденные файлы") args = parser.parse_args() if args.days < 0: parser.error("--days не может быть отрицательным") roots = default_roots() if not args.path else [] for extra in args.path: resolved = extra.expanduser().resolve() if not resolved.is_dir(): parser.error(f"Каталог не найден: {resolved}") if resolved == Path(resolved.anchor): parser.error(f"Нельзя использовать корень: {resolved}") roots.append(resolved) if not roots: print("Папки Pictures и Desktop не найдены. Укажите --path.") return 0 cutoff = time.time() - args.days * 86400 found: list[tuple[Path, int, float]] = [] seen: set[Path] = set() for root in roots: for current, dirnames, filenames in os.walk(root, followlinks=False): dirnames[:] = [ name for name in dirnames if not os.path.islink(os.path.join(current, name)) ] for name in filenames: if not looks_like_screenshot(name): continue path = Path(current) / name if path.suffix.lower() not in EXTENSIONS or path.is_symlink(): continue try: stat = path.stat() except OSError: continue if stat.st_mtime > cutoff: continue resolved = path.resolve() if resolved in seen: continue seen.add(resolved) found.append((path, stat.st_size, stat.st_mtime)) found.sort(key=lambda item: item[2]) total = sum(item[1] for item in found) print(f"Скриншотов старше {args.days} дней: {len(found)}, объём: {total / 1048576:.1f} MB") for path, size, modified in found[:30]: stamp = time.strftime("%Y-%m-%d", time.localtime(modified)) print(f" {size / 1048576:8.1f} MB {stamp} {path}") if len(found) > 30: print(f" ... и ещё {len(found) - 30} файлов") if not args.apply: print("Предпросмотр. Для удаления добавьте --apply.") return 0 deleted = 0 freed = 0 errors = 0 for path, size, _ in found: try: path.unlink() deleted += 1 freed += size except OSError as error: errors += 1 print(f"Не удалось удалить {path}: {error}") print(f"Удалено: {deleted}, освобождено: {freed / 1048576:.1f} MB, ошибок: {errors}") return 0 if __name__ == "__main__": raise SystemExit(main())