"""A bot in its own process, spoken to one JSON line at a time. Start it with python -s, not -I: -I would ignore the fixed PYTHONHASHSEED that makes a bot that iterates over sets play the same game twice. The referee never imports a bot: it starts the bot's adapter (a small child program each game has, which loads the bot in the game's own interface) and sends it one line per turn. A move that takes longer than the time limit, or a bot that crashed, gets the game's default move; the referee counts those as errors. The child side is `serve(handle)`. """ import json, os, select, subprocess, sys, time class Child: def __init__(self, argv, cwd=None, limit=1.0, start=10.0): self.limit, self.errors, self.dead = limit, 0, False env = {k: v for k, v in os.environ.items() if not k.startswith(('SS_', 'SLURM_'))} # a bot sees no job token env['PYTHONHASHSEED'] = '0' # the same bot plays the same moves: sets iterate in one order self.p = subprocess.Popen(argv, cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, env=env) self.buf, self.n = b'', 0 self.ask({'hello': True}, limit=start) def ask(self, msg, limit=None): """The child's answer to one message, or None when it is late, broken or gone.""" if self.dead: return None try: self.n += 1 # numbered, so a late answer to an earlier turn is dropped rather than taken for this one self.p.stdin.write((json.dumps({**msg, 'n': self.n}) + '\n').encode()) self.p.stdin.flush() deadline = time.monotonic() + (limit or self.limit) fd = self.p.stdout.fileno() while True: # read the pipe ourselves: a buffered readline after select can hide an answer already read while b'\n' not in self.buf: ready, _, _ = select.select([fd], [], [], max(0.0, deadline - time.monotonic())) chunk = os.read(fd, 1 << 16) if ready else b'' if not chunk: raise TimeoutError self.buf += chunk line, self.buf = self.buf.split(b'\n', 1) try: # lines that are not an answer (a library printing as it loads) are skipped msg_in = json.loads(line) except ValueError: continue if isinstance(msg_in, dict) and 'answer' in msg_in and msg_in.get('n') == self.n: return msg_in['answer'] except Exception: self.errors += 1 if self.errors >= 20 or self.p.poll() is not None: # ponytail: a slow bot is stopped after 20 misses self.close() return None def close(self): self.dead = True try: self.p.kill() except Exception: pass def serve(handle): """The child's loop: each line from the referee in, handle(message) out; {'hello': True} answers at once.""" out = sys.__stdout__ sys.stdout = sys.stderr # a bot's prints must not corrupt the channel for line in sys.stdin: msg = json.loads(line) answer = True if msg.get('hello') else handle(msg) out.write(json.dumps({'answer': answer, 'n': msg.get('n')}) + '\n') out.flush() def load(path, *names): """The first of names defined by the bot file at path, which may import its neighbours.""" import importlib.util sys.path.insert(0, os.path.dirname(os.path.abspath(path))) spec = importlib.util.spec_from_file_location('bot', path) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) for n in names: if hasattr(mod, n): return getattr(mod, n) fns = [v for v in vars(mod).values() if callable(v) and getattr(v, '__module__', '') == 'bot'] if not fns: raise SystemExit(f'{path} defines none of {", ".join(names)}') return fns[-1] # Kaggle's rule: the last function in the file