"""Run generated Python in a separate interpreter (isolated mode, time limit) and return JSON-able results. run_calls(src, entry, calls, kind="function") kind="function": each call is a list of positional args for entry(*args) kind="class": each call is {"init": [...], "ops": [["method", arg, ...], ...]}; the result is the list of method return values Returns a list with one {"ok": value} or {"err": "Type: message"} per call, or raises RunError on a crash/timeout of the whole run. Values are converted to JSON (tuples become lists, sets become sorted lists). """ from __future__ import annotations import json import os import subprocess import sys import tempfile import time HARNESS = r''' import copy, json, sys def _j(v): if isinstance(v, (list, tuple)): return [_j(x) for x in v] if isinstance(v, set): return sorted(_j(x) for x in v) if isinstance(v, dict): return {str(k): _j(x) for k, x in v.items()} if isinstance(v, float): return round(v, 9) return v _SRC = open(sys.argv[1], encoding="utf-8").read() _g = {"__name__": "solution"} exec(compile(_SRC, "solution.py", "exec"), _g) _entry, _kind = sys.argv[2], sys.argv[3] _calls = json.load(open(sys.argv[4], encoding="utf-8")) _out = [] for _c in _calls: try: if _kind == "function": _out.append({"ok": _j(_g[_entry](*copy.deepcopy(_c)))}) else: _obj = _g[_entry](*_c["init"]) _res = [] for _op in _c["ops"]: _res.append(_j(getattr(_obj, _op[0])(*copy.deepcopy(_op[1:])))) _out.append({"ok": _res}) except Exception as _e: _out.append({"err": type(_e).__name__ + ": " + str(_e)[:200]}) print(json.dumps(_out)) ''' class RunError(Exception): pass def run_calls(src: str, entry: str, calls: list, kind: str = "function", timeout: float = 10.0) -> tuple[list, float]: with tempfile.TemporaryDirectory() as d: sp, hp, cp = (os.path.join(d, n) for n in ("solution.py", "harness.py", "calls.json")) open(sp, "w", encoding="utf-8").write(src) open(hp, "w", encoding="utf-8").write(HARNESS) json.dump(calls, open(cp, "w", encoding="utf-8")) t0 = time.time() try: r = subprocess.run([sys.executable, "-I", hp, sp, entry, kind, cp], capture_output=True, text=True, timeout=timeout, cwd=d) except subprocess.TimeoutExpired: raise RunError(f"timeout after {timeout}s") dt = time.time() - t0 if r.returncode != 0: raise RunError((r.stderr or r.stdout)[-600:]) try: return json.loads(r.stdout.strip().splitlines()[-1]), dt except (ValueError, IndexError): raise RunError("no result: " + (r.stdout + r.stderr)[-400:]) def run_script(src: str, timeout: float = 10.0) -> tuple[int, str]: """Run a whole script (e.g. a test file); returns (exit code, combined output).""" with tempfile.TemporaryDirectory() as d: p = os.path.join(d, "main.py") open(p, "w", encoding="utf-8").write(src) try: r = subprocess.run([sys.executable, "-I", p], capture_output=True, text=True, timeout=timeout, cwd=d) except subprocess.TimeoutExpired: return 124, f"timeout after {timeout}s" return r.returncode, (r.stdout + r.stderr)