"""Command: the authority to run one program, with its leading arguments fixed. Each part of the box gets the commands it needs and no others: the mics get arecord, not aplay; the brain gets ask-client bound to the brain's URL, and can't point it elsewhere. """ import asyncio from asyncio.subprocess import PIPE # a constant: no authority class Command: """One program, and the arguments every use of it starts with. exec_ is asyncio.create_subprocess_exec, or a fake: >>> class Proc: ... returncode = 0 ... async def communicate(self, stdin): return (b"heard: " + stdin, b"") >>> async def fake_exec(*argv, **pipes): ... print(argv) ... return Proc() >>> hear = Command(fake_exec, "/bin/hear-client", "ws://home:8024/") >>> asyncio.run(hear.run(stdin=b"clip")) ('/bin/hear-client', 'ws://home:8024/') b'heard: clip' """ def __init__(self, exec_, *fixed): self.__exec, self.__fixed = exec_, fixed self.name = fixed[0].rsplit("/", 1)[-1] async def spawn(self, *args, stdin=True, stdout=True, stderr=True): """Start it; True means a pipe to that stream. Returns the process.""" return await self.__exec(*self.__fixed, *args, stdin=PIPE if stdin else None, stdout=PIPE if stdout else None, stderr=PIPE if stderr else None) async def start(self, *args): """Start it and let it run: no pipes, not waited for.""" return await self.spawn(*args, stdin=False, stdout=False, stderr=False) async def run(self, *args, stdin=b"", timeout=60): """Run it with stdin; return its stdout, or raise IOError with its stderr.""" proc = await self.spawn(*args) out, err = await asyncio.wait_for(proc.communicate(stdin), timeout) if proc.returncode: raise IOError(f"{self.name} exit {proc.returncode}: {err.decode().strip()}") return out