macOS

Удалить недоступные симуляторы

Находит симуляторы iOS, watchOS и tvOS без доступного runtime и удаляет их по флагу --apply

Python macOS Средний
Скачать cleanup_simulators.py
Описание

Что делает скрипт

Скрипт читает список устройств через xcrun simctl list devices --json. Недоступные устройства появляются после удаления старых runtime и занимают место. По умолчанию показывается список, удаление выполняется только с --apply и подтверждением.

Перед запуском
  • Удаляет устройства симуляторов вместе с их данными.
Запуск

Быстрый старт

python3 cleanup_simulators.py

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. В Linux и macOS интерпретатор может называться python3, в Windows - python или py.

Примеры

Другие варианты

  • python3 cleanup_simulators.py
  • python3 cleanup_simulators.py --apply
  • python3 cleanup_simulators.py --json simulators.json
Зависимости

Что понадобится

Python 3.10+ Только стандартная библиотека
macOS brew install python
Xcode Command Line Tools Нужны xcrun, codesign, stapler и компиляторы
macOS xcode-select --install
mas CLI для установки приложений из App Store
macOS brew install mas
Xcode Полная установка Xcode нужна для xcodebuild и simctl
macOS mas install 497799835
Исходник

cleanup_simulators.py

#!/usr/bin/env python3
"""Поиск и удаление недоступных симуляторов Xcode."""
from __future__ import annotations

import argparse
import json
import subprocess
import sys
from pathlib import Path


def simctl(*args: str) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        ["xcrun", "simctl", *args],
        capture_output=True,
        text=True,
        check=False,
    )


def main() -> int:
    parser = argparse.ArgumentParser(description="Удалить недоступные симуляторы")
    parser.add_argument("--apply", action="store_true", help="Удалить найденные устройства")
    parser.add_argument("--yes", action="store_true", help="Не задавать вопросов")
    parser.add_argument("--json", type=Path, help="Сохранить отчёт")
    args = parser.parse_args()

    result = simctl("list", "devices", "--json")
    if result.returncode != 0:
        print(f"xcrun simctl завершился с ошибкой: {result.stderr.strip()}", file=sys.stderr)
        return 2

    try:
        data = json.loads(result.stdout)
    except json.JSONDecodeError as error:
        print(f"Не удалось разобрать JSON simctl: {error}", file=sys.stderr)
        return 2

    runtimes = data.get("devices", {})
    devices: list[dict] = []
    for runtime, items in runtimes.items():
        for item in items:
            item = dict(item)
            item["runtime"] = runtime
            devices.append(item)

    unavailable = [item for item in devices if not item.get("isAvailable", True)]
    report = {
        "runtimes": len(runtimes),
        "devices": len(devices),
        "unavailable": [
            {
                "name": item.get("name", "?"),
                "udid": item.get("udid", ""),
                "runtime": item.get("runtime", ""),
                "state": item.get("state", ""),
                "error": item.get("availabilityError", ""),
            }
            for item in unavailable
        ],
    }

    if args.json:
        args.json.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")

    print(f"Runtime: {report['runtimes']}. Устройств: {report['devices']}. Недоступных: {len(unavailable)}.")
    for item in report["unavailable"]:
        print(f"  {item['name']} [{item['runtime']}] {item['udid']}")
        if item["error"]:
            print(f"    причина: {item['error']}")

    if not unavailable:
        return 0
    if not args.apply:
        print("Это предпросмотр. Добавьте --apply для удаления.")
        return 0
    if not args.yes:
        answer = input("Удалить недоступные симуляторы? [y/N]: ").strip().lower()
        if answer not in {"y", "yes", "д", "да"}:
            print("Отменено.")
            return 1

    errors = 0
    for item in unavailable:
        udid = item.get("udid", "")
        if not udid:
            continue
        deleted = simctl("delete", udid)
        if deleted.returncode == 0:
            print(f"Удалён: {item.get('name', udid)}")
        else:
            errors += 1
            print(f"Ошибка удаления {item.get('name', udid)}: {deleted.stderr.strip()}")

    print(f"Готово. Ошибок: {errors}.")
    return 0 if errors == 0 else 1


if __name__ == "__main__":
    raise SystemExit(main())

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get macos-simulators-cleanup
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

macOS

Shell, Python и автоматизация macOS без лишних приложений.