8 from typing import List, Optional
11 logger = logging.getLogger(__file__)
14 def cmd_showing_output(command: str) -> None:
15 line_enders = set([b'\n', b'\r'])
20 stdout=subprocess.PIPE,
21 stderr=subprocess.PIPE,
22 universal_newlines=False,
24 for char in iter(lambda: p.stdout.read(1), b''):
25 sys.stdout.buffer.write(char)
26 if char in line_enders:
31 def cmd_with_timeout(command: str, timeout_seconds: Optional[float]) -> int:
33 Run a command but do not let it run for more than timeout seconds.
35 >>> cmd_with_timeout('/bin/echo foo', 10.0)
38 >>> cmd_with_timeout('/bin/sleep 2', 0.1)
39 Traceback (most recent call last):
41 subprocess.TimeoutExpired: Command '['/bin/bash', '-c', '/bin/sleep 2']' timed out after 0.1 seconds
44 return subprocess.check_call(
45 ["/bin/bash", "-c", command], timeout=timeout_seconds
49 def cmd(command: str, timeout_seconds: Optional[float] = None) -> str:
50 """Run a command with everything encased in a string and return
51 the output text as a string. Raises subprocess.CalledProcessError.
53 >>> cmd('/bin/echo foo')[:-1]
56 >>> cmd('/bin/sleep 2', 0.1)
57 Traceback (most recent call last):
59 subprocess.TimeoutExpired: Command '/bin/sleep 2' timed out after 0.1 seconds
63 command, shell=True, capture_output=True, check=True, timeout=timeout_seconds,
65 return ret.decode("utf-8")
68 def run_silently(command: str) -> None:
69 """Run a command silently but raise subprocess.CalledProcessError if
72 >>> run_silently("/usr/bin/true")
74 >>> run_silently("/usr/bin/false")
75 Traceback (most recent call last):
77 subprocess.CalledProcessError: Command '/usr/bin/false' returned non-zero exit status 1.
81 command, shell=True, stderr=subprocess.DEVNULL,
82 stdout=subprocess.DEVNULL, capture_output=False, check=True
86 def cmd_in_background(
87 command: str, *, silent: bool = False
88 ) -> subprocess.Popen:
89 args = shlex.split(command)
91 subproc = subprocess.Popen(args,
92 stdin=subprocess.DEVNULL,
93 stdout=subprocess.DEVNULL,
94 stderr=subprocess.DEVNULL)
96 subproc = subprocess.Popen(args, stdin=subprocess.DEVNULL)
98 def kill_subproc() -> None:
100 if subproc.poll() is None:
101 logger.info("At exit handler: killing {}: {}".format(subproc, command))
103 subproc.wait(timeout=10.0)
104 except BaseException as be:
106 atexit.register(kill_subproc)
110 def cmd_list(command: List[str]) -> str:
111 """Run a command with args encapsulated in a list and return the
112 output text as a string. Raises subprocess.CalledProcessError.
114 ret = subprocess.run(command, capture_output=True, check=True).stdout
115 return ret.decode("utf-8")
118 if __name__ == '__main__':