+ def timer_expired(p):
+ p.kill()
+ raise subprocess.TimeoutExpired(command, timeout_seconds)
+
+ line_enders = set([b'\n', b'\r'])
+ sel = selectors.DefaultSelector()
+ with subprocess.Popen(
+ command,
+ shell=True,
+ bufsize=0,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ universal_newlines=False,
+ ) as p:
+ timer = None
+ if timeout_seconds:
+ import threading
+
+ timer = threading.Timer(timeout_seconds, timer_expired(p))
+ timer.start()
+ try:
+ sel.register(p.stdout, selectors.EVENT_READ) # type: ignore
+ sel.register(p.stderr, selectors.EVENT_READ) # type: ignore
+ done = False
+ while not done:
+ for key, _ in sel.select():
+ char = key.fileobj.read(1) # type: ignore
+ if not char:
+ sel.unregister(key.fileobj)
+ if len(sel.get_map()) == 0:
+ sys.stdout.flush()
+ sys.stderr.flush()
+ sel.close()
+ done = True
+ if key.fileobj is p.stdout:
+ os.write(sys.stdout.fileno(), char)
+ if char in line_enders:
+ sys.stdout.flush()
+ else:
+ os.write(sys.stderr.fileno(), char)
+ if char in line_enders:
+ sys.stderr.flush()
+ p.wait()
+ finally:
+ if timer:
+ timer.cancel()
+ return p.returncode
+
+
+def cmd_exitcode(command: str, timeout_seconds: Optional[float] = None) -> int:
+ """Run a command silently and return its exit code once it has
+ finished. If timeout_seconds is provided and the command runs too
+ long it will raise a TimeoutExpired exception.
+
+ Args:
+ command: the command to run
+ timeout_seconds: the max number of seconds to allow the subprocess
+ to execute or None to indicate no timeout
+
+ Returns:
+ the exit status of the subprocess once the subprocess has
+ exited
+
+ >>> cmd_exitcode('/bin/echo foo', 10.0)