# SPDX-License-Identifier: GPL-3.0-or-later """``run.py``: Mesen2 runs speaking the emu-tools contract (manifest, formats, exit codes). python3 -I run.py --machine nes|snes|pce|snes-cx4 --rom PATH --out DIR [--frames N] [--until log:TEXT] [--frames-out] [--frames-at F,F] [--trace KIND[,KIND]] [--trace-window START:END] [--input FILE] [--lua FILE] [--reset-at N] [--power-on-ram zeros|ones|random] [--region R] [--no-sprites] [--fds-bios PATH] [--audio-out] [--nes-...] [--hold-test] [--seed N] [--lib PATH] [--timeout S] python3 -I run.py --batch FILE [--lib PATH] python3 -I run.py --version The README lists each machine's settings, traces and outputs. One run per process, or a batch of runs in one process that starts the library once (``--batch``; the library cannot start a second time in one process, OBSERVED, so a batch keeps it between runs). """ from __future__ import annotations import argparse import gzip import hashlib import json import os import re import sys import zipfile from pathlib import Path from . import CORES, TOOL, VERSION, api, cx4, inputs, lua, manifest, nes, pce, snes MACHINES = { "nes": "NES-001 settings for comparison: identity palette, RAM as --power-on-ram (zeros by " "default), standard pads, PPU writes ignored until the first pre-render line, OAM row " "corruption on", "snes": "SNES: standard pads, region NTSC unless --region, RAMs as --power-on-ram (zeros by " "default), every frame drawn (no frame skipping)", "pce": "PC Engine / TurboGrafx-16 / SuperGrafx (Mesen2 chooses by the card): RGB333 palette, " "RAM as --power-on-ram (zeros by default), no frame skipping, a pad only with --input", "snes-cx4": "SNES with a Cx4 cartridge: as snes, plus the Cx4 trace and the host stream", } TRACES = { "nes": {"insn"}, "snes": set(), "pce": set(), "snes-cx4": {"cx4-text", "host"}, } EXIT_OK, EXIT_CHECK, EXIT_USAGE, EXIT_MISSING = 0, 1, 2, 3 #: --power-on-ram as Mesen2's RamState. POWER_ON_RAM = {"zeros": 1, "ones": 2, "random": 0} #: The player's Famicom Disk System BIOS, when --fds-bios is not given. FDS_BIOS_VARIABLE = "FDS_BIOS" FDS_BIOS_SIZE = 0x2000 #: The NES trace logger line the runner parses into trace/insn records. NES_INSN_FORMAT = ( b"PC:[PC,4h] OP:[ByteCode,h] |A:[A,2h] X:[X,2h] Y:[Y,2h] S:[SP,2h] P:[P,2h] " b"CYC:[CycleCount] SL:[Scanline] DOT:[Cycle] FR:[FrameCount]" ) NES_INSN = re.compile( r"PC:([0-9A-Fa-f]{4}) OP:([^|]*)\|A:([0-9A-Fa-f]{2}) X:([0-9A-Fa-f]{2}) Y:([0-9A-Fa-f]{2}) " r"S:([0-9A-Fa-f]{2}) P:([0-9A-Fa-f]{2}) CYC:(\d+) SL:(-?\d+) DOT:(\d+) FR:(\d+)" ) #: The marker the runner's last script logs at the end of the last frame (``lua.DONE_LAST_LUA``), #: and as it appears in the log: the runner's own lines carry ``lua.TAG``, so script-log.txt #: keeps exactly the player's lines, whatever their format. RUN_DONE = "RUN-DONE" RUN_MARK = lua.TAG + RUN_DONE #: What the frame scripts log after their picture (no longer the end of the run). PIXELS_DONE = "PIXELS-DONE" #: What ``--until`` takes: ``log:TEXT``, a line the player's script logs that starts with TEXT. UNTIL_LOG = "log:" class Usage(Exception): pass class Missing(Exception): pass def parser() -> argparse.ArgumentParser: p = argparse.ArgumentParser(prog="run.py", description="Run Mesen2 headless as a closed box.") p.add_argument("--version", action="store_true", help="print the version and the pin") p.add_argument("--batch", type=Path, help="run each line of FILE (a JSON object of options) in this one process") # fmt: skip p.add_argument("--machine", choices=sorted(MACHINES)) p.add_argument("--rom", type=Path, help="the program to run (a path the player supplies)") p.add_argument("--out", type=Path, help="output directory (manifest.json goes here)") p.add_argument("--frames", type=int, default=60, help="frames to run (default 60; with --until or emu.stop, at most this many)") # fmt: skip p.add_argument("--until", metavar="log:TEXT", help="end at the end of the frame in which the --lua script logs a line " "starting with TEXT") # fmt: skip p.add_argument("--frames-out", action="store_true", help="write the last frame as PNG") p.add_argument("--frames-at", help="nes, snes: also write these frames (comma-separated) as PNG") p.add_argument("--audio-out", action="store_true", help="nes: record audio.wav (a run of its own)") p.add_argument("--nes-ppu-reset-at-power", choices=("on", "off"), default="on", help="nes: PPU writes ignored until the first pre-render line (default on)") p.add_argument("--nes-oam-row-corruption", choices=("on", "off"), default="on", help="nes: OAM row corruption (default on; off for the Vs. System's RGB PPUs)") p.add_argument("--nes-apu", choices=("on", "off"), default="on", help="nes --audio-out: the APU's five channels (off: a cartridge's sound alone)") p.add_argument("--fds-bios", type=Path, help=f"nes: the player's Disk System BIOS (8 KiB, loose or in a .zip; else " f"{FDS_BIOS_VARIABLE})") # fmt: skip p.add_argument("--trace", default="", help="traces to write, comma-separated") p.add_argument("--trace-window", help="snes-cx4: START:END frames to trace") p.add_argument("--input", type=Path, help="controller input script (JSON Lines)") p.add_argument("--lua", type=Path, help="an extra Lua script; its log goes to script-log.txt") p.add_argument("--reset-at", type=int, metavar="N", help="press the console's reset button at the end of frame N") # fmt: skip p.add_argument("--power-on-ram", choices=sorted(POWER_ON_RAM), default="zeros", help="what the RAMs hold at power-on (default zeros; random is Mesen2's own, " "not seeded)") # fmt: skip p.add_argument("--no-sprites", action="store_true", help="pce: Mesen2's sprite switch off") p.add_argument("--region", choices=("ntsc", "pal", "dendy", "auto"), help="nes, snes") p.add_argument("--seed", type=int, default=0, help="recorded; the settings leave no randomness") p.add_argument("--core", choices=sorted(CORES), help="the pinned core whose own build to run (build.sh --core NAME); " "without it, MESEN_CORE, else Mesen2's build") # fmt: skip p.add_argument("--lib", type=Path, help="MesenCore.so (else --core's build, else MESEN_CORE, " "else build.sh's Mesen2)") # fmt: skip p.add_argument("--timeout", type=float, default=300.0, help="wall-clock seconds") p.add_argument("--hold-test", action="store_true", help="snes-cx4: hold pad 2 B from power-on") return p def missing_library(core: str | None, lib: Path | None) -> str: """The message for a library not found (exit 3), naming what was looked for.""" if core is not None: return f"no MesenCore.so at {lib}: run build.sh --core {core}, or pass --lib" return "no MesenCore.so: run build.sh, set MESEN_CORE or pass --lib" def version_line() -> str: cores = "; ".join(f"{c['name']} {c['commit'][:7]}, {c['licence']}" for c in CORES.values()) return f"{TOOL} {VERSION} ({cores})" def save_png(path: Path, width: int, height: int, rgb: bytes | None = None, values=None) -> None: from PIL import Image if rgb is not None: Image.frombytes("RGB", (width, height), rgb).save(path) else: # 16-bit grey: one buffer value a pixel image = Image.new("I;16", (width, height)) image.putdata(values) image.save(path) def nes_insn(trace: Path, out: Path) -> int: """Mesen2's NES trace text to trace/insn JSON Lines (gzipped); the record count.""" count = 0 with trace.open("r", errors="replace") as source, gzip.open(out, "wt", encoding="utf-8") as sink: for line in source: m = NES_INSN.search(line) if not m: continue pc, op, a, x, y, s, p, cyc, sl, dot, fr = m.groups() record = { "t": int(cyc), "clock": "cpu", "cpu": "main", "pc": int(pc, 16), "op": [int(b, 16) for b in op.replace("$", " ").split()], "regs": {"A": int(a, 16), "X": int(x, 16), "Y": int(y, 16), "S": int(s, 16), "P": int(p, 16)}, "line": int(sl), "dot": int(dot), "frame": int(fr), } # fmt: skip sink.write(json.dumps(record, separators=(",", ":")) + "\n") count += 1 return count def is_fds(rom: Path) -> bool: """A Famicom Disk System image: ``.fds``, or fwNES's or a raw disk's first bytes.""" if rom.suffix.lower() == ".fds": return True with rom.open("rb") as f: head = f.read(16) return head[:4] == b"FDS\x1a" or head[1:15] == b"*NINTENDO-HVC*" def fds_bios(given: Path | None) -> tuple[bytes, str]: """The player's 8 KiB BIOS and where it came from: ``--fds-bios``, else ``FDS_BIOS``; a loose file or a .zip holding one 8 KiB file. Never committed, downloaded or kept.""" source = "--fds-bios" if given is None: named = os.environ.get(FDS_BIOS_VARIABLE) if not named: raise Missing(f"an FDS image needs the player's BIOS: --fds-bios PATH or " f"{FDS_BIOS_VARIABLE}") # fmt: skip given, source = Path(named), FDS_BIOS_VARIABLE if not given.is_file(): raise Missing(f"no such FDS BIOS: {given} (from {source})") if given.suffix.lower() == ".zip": with zipfile.ZipFile(given) as archive: members = [i for i in archive.infolist() if i.file_size == FDS_BIOS_SIZE] if len(members) != 1: raise Usage(f"{given}: a BIOS zip holds one 8 KiB file, this holds {len(members)}") data = archive.read(members[0]) else: data = given.read_bytes() if len(data) != FDS_BIOS_SIZE: raise Usage(f"{given}: an FDS BIOS is 8 KiB, this is {len(data)} bytes") return data, source def read_full_log(path: Path) -> list[str]: """The lines the full-log script wrote (``lua.FULL_LOG_LUA``); the file is then emptied.""" if not path.exists(): return [] lines = path.read_text(encoding="utf-8", errors="replace").splitlines() path.write_bytes(b"") return lines def host_rows(lines: list[str], frames: int) -> dict[int, str]: """The Cx4 host stream's rows (``H tokens``) for frames 1 to ``frames``.""" rows = {} for row in lines: if row.startswith("H"): number, _, data = row[1:].partition(" ") if number.isdigit() and 1 <= int(number) <= frames: rows[int(number)] = data return rows def run(a: argparse.Namespace, argv: list[str], batch: dict | None = None) -> int: started = manifest.now() if a.machine is None or a.rom is None or a.out is None: raise Usage("--machine, --rom and --out are required") traces = {t for t in a.trace.split(",") if t} if not traces <= TRACES[a.machine]: raise Usage(f"{a.machine} traces: {sorted(TRACES[a.machine]) or 'none yet'}") if a.frames < 1: raise Usage("--frames must be at least 1") if a.reset_at is not None and not 1 <= a.reset_at < a.frames: raise Usage("--reset-at N with N from 1 to --frames minus 1") if a.reset_at is not None and a.machine == "pce": raise Usage("--reset-at is for nes, snes and snes-cx4 (on pce Mesen2's Lua reset left the " "emulator without another frame, OBSERVED 2026-11-24)") # fmt: skip if a.no_sprites and a.machine != "pce": raise Usage("--no-sprites is for pce") if not a.rom.is_file(): print(f"no such ROM: {a.rom}", file=sys.stderr) return EXIT_MISSING lib = api.find_library(a.lib, core=a.core) if lib is None or not lib.exists(): print(missing_library(a.core, lib), file=sys.stderr) return EXIT_MISSING console = "snes" if a.machine == "snes-cx4" else a.machine records = inputs.read(a.input, console) if a.input else [] if a.machine == "snes-cx4" and any(port != 1 for _, port, _ in records): raise Usage("snes-cx4 takes input for port 1 only (Lua's input call is ignored for port 2 " "in this build, OBSERVED by hg51b-python; --hold-test holds port 2's B)") # fmt: skip wanted = sorted({int(x) for x in (a.frames_at or "").split(",") if x.strip()}) if wanted and (a.machine not in ("nes", "snes") or wanted[-1] > a.frames or wanted[0] < 1): raise Usage("--frames-at is for nes and snes, with frames from 1 to --frames") until_log = None if a.until is not None: if not a.until.startswith(UNTIL_LOG) or len(a.until) == len(UNTIL_LOG): raise Usage("--until takes log:TEXT (a line your --lua script logs, starting with TEXT)") until_log = a.until[len(UNTIL_LOG) :] if a.lua is None: raise Usage("--until log:TEXT needs the --lua script that logs it") if until_log.startswith(lua.TAG.strip()) or "]==]" in until_log or "\n" in until_log: raise Usage("--until log:TEXT: TEXT may not start with the runner's tag or hold ]==]") user = inputs.lua(records) + (a.lua.read_text() if a.lua else "") if a.audio_out and (a.machine != "nes" or traces or a.frames_out or wanted or user or a.reset_at is not None or a.until is not None): # fmt: skip raise Usage("--audio-out is for nes, alone (a run of its own)") bios = None if a.machine == "nes" and is_fds(a.rom): bios = fds_bios(a.fds_bios) elif a.fds_bios is not None: raise Usage("--fds-bios is for an FDS image on machine nes") ram = POWER_ON_RAM[a.power_on_ram] a.out.mkdir(parents=True, exist_ok=True) work = a.out / "work" work.mkdir(exist_ok=True) home = work / "home" home.mkdir(exist_ok=True) full_log = work / "script-log.raw" prefix = lua.full_log_lua(full_log.resolve()) + lua.stop_until_lua(until_log) reset =lua.reset_lua(a.reset_at) if a.reset_at is not None else "" outputs: list[dict] = [] status, notes = "ok", {} notes["power_on"] = {"ram": a.power_on_ram, "random_power_on_state": "off (Mesen2's own switch, left at its default)"} # fmt: skip if a.machine == "nes": notes["switches"] = {"ppu_reset_at_power": a.nes_ppu_reset_at_power, "oam_row_corruption": a.nes_oam_row_corruption, "region": a.region or "ntsc"} # fmt: skip else: notes["frame_skipping"] = "off" if a.reset_at is not None: notes["reset_at"] = {"frame": a.reset_at, "how": "the console's reset button, at the end of that frame"} # fmt: skip if a.no_sprites: notes["sprites"] = "off (Mesen2's DisableSprites)" if batch is not None: notes["batch"] = batch firmware = home / "Firmware" / "disksys.rom" if bios is not None: firmware.parent.mkdir(exist_ok=True) firmware.write_bytes(bios[0]) log, full, own = "", [], [] last = a.frames # the run's last frame: --frames, or where emu.stop or --until ended it try: if a.machine == "nes" and a.audio_out: notes["script_log"] = "none (an audio run has no script)" nes.record_wave(lib, a.rom, a.frames, a.out / "audio.wav", home, a.timeout, apu=a.nes_apu == "on", ram=ram, exact=True) # fmt: skip import wave with wave.open(str(a.out / "audio.wav")) as w: rate, channels, count = w.getframerate(), w.getnchannels(), w.getnframes() outputs.append({"path": "audio.wav", "format": "audio/wav", "records": count, "rate": rate, "channels": channels, "note": "Mesen2's WAV recorder after its own mixer; ends where the " "emulator is held at the end of frame --frames"}) # fmt: skip elif a.machine == "nes": region = {"ntsc": 1, "pal": 2, "dendy": 3, "auto": 0, None: 1}[a.region] raw_trace = work / "nes.trace" if "insn" in traces else None logged = sorted({*wanted, a.frames}) picture = lua.NES_PICTURE_LUA if a.frames_out else "" script = (prefix + lua.wanted_lua(logged) + lua.tagged(lua.frames_lua(logged)) + user + reset + lua.tagged(lua.end_frame_lua(a.frames, RUN_DONE, picture, hold=True))) # fmt: skip code, log, _ = nes.run( lib, a.rom, lua=script.encode(), lua_name="run.lua", seconds=a.timeout, home=home, trace=raw_trace, until=RUN_MARK, for_comparison=True, region=region, trace_format=NES_INSN_FORMAT, ppu_reset_at_power=a.nes_ppu_reset_at_power == "on", oam_row_corruption=a.nes_oam_row_corruption == "on", ram=ram, script_io=True, ) # fmt: skip full = read_full_log(full_log) own = lua.untag(full)[0] collected = {} for line in own: key, _, text = line.partition(" ") if key[:1] in ("L", "E") and key[1:2].isdigit() and text: # not the END line collected[key] = text pictures = lua.decode_frames(collected) ended = lua.end_of_run(own) last = ended["frame"] if ended else a.frames if code != 0: status = "timeout" if code == -1 else f"stopped ({code})" for at in sorted({*(w for w in wanted if w <= last), *([last] if a.frames_out else [])}): if at not in pictures: status = f"frame {at} lost from the script log" if status == "ok" else status continue name = f"frame-{at:06d}.png" save_png(a.out / name, 256, len(pictures[at]) // 256, values=pictures[at]) outputs.append({"path": name, "format": "frame/png", "records": 1, "pixels": "16-bit grey: palette index | emphasis << 6 (identity palette)"}) # fmt: skip if raw_trace is not None and raw_trace.exists(): count = nes_insn(raw_trace, a.out / "insn.jsonl.gz") raw_trace.write_bytes(b"") outputs.append({"path": "insn.jsonl.gz", "format": "trace/insn", "records": count}) elif a.machine in ("snes", "pce"): picture = lua.HEX_PICTURE_LUA if a.frames_out else "" done = user + reset + lua.tagged(lua.end_frame_lua(a.frames, RUN_DONE, picture)) if a.machine == "snes": region = a.region if a.region in snes.REGIONS else "ntsc" at = lua.snes_frames_at_lua(wanted) if wanted else "" script = prefix + lua.tagged(lua.hex_frame_lua(a.frames, PIXELS_DONE)) + at + done log, _ = snes.run(lib, a.rom, a.frames, home, a.timeout, script, done=RUN_MARK, config=snes.snes_config(region, ram, no_frame_skip=True), script_io=True) # fmt: skip else: script = prefix + lua.tagged(pce.LUA.format(frames=a.frames, done=PIXELS_DONE)) + done log, _ = pce.run(lib, a.rom, a.frames, home, a.timeout, no_sprites=a.no_sprites, pad=bool(records), lua=script, done=RUN_MARK, ram=ram, script_io=True) # fmt: skip full = read_full_log(full_log) own = lua.untag(full)[0] ended = lua.end_of_run(own) last = ended["frame"] if ended else a.frames if RUN_MARK not in log and RUN_DONE not in own: status = "timeout" else: size = snes.frame_size if a.machine == "snes" else pce.frame_size shots = {f: v for f, v in lua.frame_pixels(own).items() if f <= last} if a.frames_out: shots[last] = lua.hex_pixels("\n".join(own)) for at_frame in sorted(shots): count, rgb = shots[at_frame] width, height = size(count) if not width: status = f"frame of {count} pixels has no unambiguous width" continue name = f"frame-{at_frame:06d}.png" save_png(a.out / name, width, height, rgb=rgb) outputs.append({"path": name, "format": "frame/png", "records": 1, "pixels": "RGB as Mesen2's screen buffer gives it"}) # fmt: skip else: # snes-cx4 start = end = 0 if a.trace_window: first_w, _, last_w = a.trace_window.partition(":") start, end = int(first_w), int(last_w) if end <= start: raise Usage("--trace-window START:END with END > START") if "cx4-text" not in traces: start = end = 0 region = a.region if a.region in snes.REGIONS else "ntsc" picture = lua.HEX_PICTURE_LUA if a.frames_out else "" log, _ = cx4.run(lib, a.rom, work, test=a.hold_test, frames=a.frames, trace_start=start, trace_frames=end - start, host="host" in traces, timeout=a.timeout, prefix_lua=prefix, extra_lua=user + reset + lua.tagged( lua.end_frame_lua(a.frames, RUN_DONE, picture, hold=True)), done=PIXELS_DONE, until=RUN_MARK, tag=True, config=snes.snes_config(region, ram, no_frame_skip=True), script_io=True) # fmt: skip full = read_full_log(full_log) own = lua.untag(full)[0] ended = lua.end_of_run(own) last = ended["frame"] if ended else a.frames lines_traced = cx4.finish_trace(work) if lines_traced is not None: (work / "cx4.trace.gz").rename(a.out / "cx4.trace.gz") outputs.append({"path": "cx4.trace.gz", "format": "mesen2/cx4-text", "records": lines_traced}) # fmt: skip if "host" in traces: # From the full log: every frame's row, exactly frames 1 to the last. rows = host_rows(own, last) with gzip.open(a.out / "host.txt.gz", "wt", encoding="ascii") as sink: for number in sorted(rows): sink.write(f"{number} {rows[number]}\n") outputs.append({"path": "host.txt.gz", "format": "mesen2/cx4-host", "records": len(rows)}) # fmt: skip missing = [n for n in range(1, last + 1) if n not in rows] print(f"host stream: {len(rows)} of {last} frames" + (f", {len(missing)} missing: {missing[:10]}" if missing else ", complete") + f": {a.out / 'host.txt.gz'}") # fmt: skip if missing and status == "ok": status = f"host stream: {len(missing)} frames missing" if RUN_MARK not in log and RUN_DONE not in own: status = "timeout" elif a.frames_out: count, rgb = lua.hex_pixels("\n".join(own)) width, height = snes.frame_size(count) name = f"frame-{last:06d}.png" save_png(a.out / name, width, height, rgb=rgb) outputs.append({"path": name, "format": "frame/png", "records": 1}) finally: if bios is not None: firmware.unlink(missing_ok=True) # the run's copy of the player's BIOS: never kept if not (a.machine == "nes" and a.audio_out): if not full and status == "ok": status = "the full script log was not written (Lua's io library unavailable?)" notes["script_log"] = ("complete: every emu.log line, written as logged through Lua's io " "library (allowed for this run)") # fmt: skip seen = set(full) # Only what Mesen2 logged up to the runner's marker: the SNES and the PC Engine run on # while the runner stops them, and the player's lines from those frames are not Mesen2's. before_end = log.split(RUN_MARK)[0] messages = [x for x in before_end.splitlines() if x and x not in seen] if messages: # Mesen2's own lines (script loading, Lua errors), from its last 500 notes["script_messages"] = messages[:20] ended = lua.end_of_run(own) if ended is not None or until_log is not None: # How the run ended, when it was not simply --frames frames: the player's emu.stop # (its code; the run itself succeeded, so the exit status stays 0) or --until. end = ended or {"by": "frames", "frame": a.frames} if until_log is not None: end["until"] = a.until end["reached"] = end["by"] == "until" late = [f for f in wanted if f > end["frame"]] if late: end["frames_not_reached"] = late notes["end"] = end script_lines = lua.untag(full)[1] # every line but the runner's own if a.lua: (a.out / "script-log.txt").write_text("\n".join(script_lines) + "\n", encoding="utf-8") outputs.append({"path": "script-log.txt", "format": "text", "records": len(script_lines)}) found = [{"role": "rom", "sha1": manifest.sha1(a.rom), "size": a.rom.stat().st_size}] if a.input: found.append({"role": "input", "sha1": manifest.sha1(a.input), "size": a.input.stat().st_size}) if bios is not None: found.append({"role": "bios", "sha1": hashlib.sha1(bios[0]).hexdigest(), "size": len(bios[0]), "from": bios[1]}) # fmt: skip manifest.write( a.out, machine=a.machine, args=argv, inputs=found, lib=lib, outputs=outputs, status=status, seed=a.seed, started=started, extra={"settings": MACHINES[a.machine], **notes}, ) # fmt: skip return EXIT_OK if status == "ok" else EXIT_CHECK #: Options a batch line may not set: the library is the batch's, started once. BATCH_ONLY = {"batch", "core", "lib", "version"} def line_args(row: dict) -> list[str]: """A batch line's options as a command line: ``{"machine": "nes", "frames-out": true}`` -> ``--machine nes --frames-out`` (underscores may stand for hyphens; false or null leaves an option out).""" if not isinstance(row, dict): raise Usage("a batch line is a JSON object of options") argv = [] for key, value in row.items(): name = str(key).lstrip("-").replace("_", "-") if name in BATCH_ONLY: raise Usage(f"--{name} is the batch's own, not a line's") if value is True: argv.append(f"--{name}") elif value not in (False, None): argv += [f"--{name}", str(value)] return argv def batch(a: argparse.Namespace, p: argparse.ArgumentParser) -> int: """Every line of ``a.batch`` as a run of its own, in this process, the library started once. One summary line of JSON per run on standard output; exit 0 when every run exited 0, else 1 (each run's status is in its summary line and its manifest).""" if not a.batch.is_file(): print(f"no such batch file: {a.batch}", file=sys.stderr) return EXIT_MISSING lib = api.find_library(a.lib, core=a.core) if lib is None or not lib.exists(): print(missing_library(a.core, lib), file=sys.stderr) return EXIT_MISSING text = a.batch.read_bytes() about = {"file": a.batch.name, "sha1": hashlib.sha1(text).hexdigest()} api.KEEP = True worst = EXIT_OK for number, line in enumerate(text.decode("utf-8").splitlines(), 1): if not line.strip() or line.lstrip().startswith("#"): continue out = None try: argv = line_args(json.loads(line)) sub = p.parse_args(argv + ["--lib", str(lib)]) out = sub.out code = run(sub, argv, batch={**about, "line": number}) except (Usage, inputs.InputError, ValueError) as error: print(f"run.py: batch line {number}: {error}", file=sys.stderr) code = EXIT_USAGE except Missing as error: print(f"run.py: batch line {number}: {error}", file=sys.stderr) code = EXIT_MISSING except SystemExit as error: # argparse's usage errors, an adapter's LoadRom failure if not isinstance(error.code, int): print(f"run.py: batch line {number}: {error.code}", file=sys.stderr) code = error.code if isinstance(error.code, int) else EXIT_CHECK print(json.dumps({"batch_line": number, "out": str(out) if out else None, "exit": code}), flush=True) # fmt: skip if code != EXIT_OK: worst = EXIT_CHECK return worst def main(argv: list[str] | None = None) -> int: argv = sys.argv[1:] if argv is None else argv p = parser() a = p.parse_args(argv) if a.version: print(version_line()) return EXIT_OK try: if a.batch is not None: if a.machine or a.rom or a.out: raise Usage("--batch takes its runs from the file (and --core or --lib), nothing else") return batch(a, p) return run(a, argv) except Usage as error: p.print_usage(sys.stderr) print(f"run.py: {error}", file=sys.stderr) return EXIT_USAGE except inputs.InputError as error: print(f"run.py: {error}", file=sys.stderr) return EXIT_USAGE except Missing as error: print(f"run.py: {error}", file=sys.stderr) return EXIT_MISSING