- )
- for line in iter(p.stdout.readline, b''):
- print(line.decode('utf-8'), end='')
- p.stdout.close()
- p.wait()
-
-
-def cmd_with_timeout(command: str, timeout_seconds: Optional[float]) -> int:
- """
- Run a command but do not let it run for more than timeout seconds.
-
- >>> cmd_with_timeout('/bin/echo foo', 10.0)
+ 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)