- )
- sel = selectors.DefaultSelector()
- sel.register(p.stdout, selectors.EVENT_READ)
- sel.register(p.stderr, selectors.EVENT_READ)
- should_exit = False
- while not should_exit:
- for key, _ in sel.select():
- char = key.fileobj.read(1)
- if not char:
- should_exit = True
- if key.fileobj is p.stdout:
- sys.stdout.buffer.write(char)
- if char in line_enders:
- sys.stdout.flush()
- else:
- sys.stderr.buffer.write(char)
- if char in line_enders:
- sys.stderr.flush()
- p.wait()
- return p.returncode
-
-
-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.
- Doesn't capture or rebroadcast command output. Function returns
- the exit value of the command or raises a TimeoutExpired exception
- if the deadline is exceeded.
-
- >>> cmd_with_timeout('/bin/echo foo', 10.0)
+ ) 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)