7 from typing import List, Optional
10 logger = logging.getLogger(__file__)
13 def cmd_with_timeout(command: str, timeout_seconds: Optional[float]) -> int:
15 Run a command but do not let it run for more than timeout seconds.
17 >>> cmd_with_timeout('/bin/echo foo', 10.0)
20 >>> cmd_with_timeout('/bin/sleep 2', 0.1)
21 Traceback (most recent call last):
23 subprocess.TimeoutExpired: Command '['/bin/bash', '-c', '/bin/sleep 2']' timed out after 0.1 seconds
26 return subprocess.check_call(
27 ["/bin/bash", "-c", command], timeout=timeout_seconds
31 def cmd(command: str, timeout_seconds: Optional[float] = None) -> str:
32 """Run a command with everything encased in a string and return
33 the output text as a string. Raises subprocess.CalledProcessError.
35 >>> cmd('/bin/echo foo')[:-1]
38 >>> cmd('/bin/sleep 2', 0.1)
39 Traceback (most recent call last):
41 subprocess.TimeoutExpired: Command '/bin/sleep 2' timed out after 0.1 seconds
45 command, shell=True, capture_output=True, check=True, timeout=timeout_seconds,
47 return ret.decode("utf-8")
50 def run_silently(command: str) -> None:
51 """Run a command silently but raise subprocess.CalledProcessError if
54 >>> run_silently("/usr/bin/true")
56 >>> run_silently("/usr/bin/false")
57 Traceback (most recent call last):
59 subprocess.CalledProcessError: Command '/usr/bin/false' returned non-zero exit status 1.
63 command, shell=True, stderr=subprocess.DEVNULL,
64 stdout=subprocess.DEVNULL, capture_output=False, check=True
68 def cmd_in_background(
69 command: str, *, silent: bool = False
70 ) -> subprocess.Popen:
71 args = shlex.split(command)
73 subproc = subprocess.Popen(args,
74 stdin=subprocess.DEVNULL,
75 stdout=subprocess.DEVNULL,
76 stderr=subprocess.DEVNULL)
78 subproc = subprocess.Popen(args, stdin=subprocess.DEVNULL)
80 def kill_subproc() -> None:
82 if subproc.poll() is None:
83 logger.info("At exit handler: killing {}: {}".format(subproc, command))
85 subproc.wait(timeout=10.0)
86 except BaseException as be:
88 atexit.register(kill_subproc)
92 def cmd_list(command: List[str]) -> str:
93 """Run a command with args encapsulated in a list and return the
94 output text as a string. Raises subprocess.CalledProcessError.
96 ret = subprocess.run(command, capture_output=True, check=True).stdout
97 return ret.decode("utf-8")
100 if __name__ == '__main__':