7 from typing import List, Optional
10 logger = logging.getLogger(__file__)
13 def cmd_showing_output(command: str) -> None:
18 stdout=subprocess.PIPE,
19 stderr=subprocess.PIPE,
21 for line in iter(p.stdout.readline, b''):
22 print(line.decode('utf-8'), end='')
27 def cmd_with_timeout(command: str, timeout_seconds: Optional[float]) -> int:
29 Run a command but do not let it run for more than timeout seconds.
31 >>> cmd_with_timeout('/bin/echo foo', 10.0)
34 >>> cmd_with_timeout('/bin/sleep 2', 0.1)
35 Traceback (most recent call last):
37 subprocess.TimeoutExpired: Command '['/bin/bash', '-c', '/bin/sleep 2']' timed out after 0.1 seconds
40 return subprocess.check_call(
41 ["/bin/bash", "-c", command], timeout=timeout_seconds
45 def cmd(command: str, timeout_seconds: Optional[float] = None) -> str:
46 """Run a command with everything encased in a string and return
47 the output text as a string. Raises subprocess.CalledProcessError.
49 >>> cmd('/bin/echo foo')[:-1]
52 >>> cmd('/bin/sleep 2', 0.1)
53 Traceback (most recent call last):
55 subprocess.TimeoutExpired: Command '/bin/sleep 2' timed out after 0.1 seconds
59 command, shell=True, capture_output=True, check=True, timeout=timeout_seconds,
61 return ret.decode("utf-8")
64 def run_silently(command: str) -> None:
65 """Run a command silently but raise subprocess.CalledProcessError if
68 >>> run_silently("/usr/bin/true")
70 >>> run_silently("/usr/bin/false")
71 Traceback (most recent call last):
73 subprocess.CalledProcessError: Command '/usr/bin/false' returned non-zero exit status 1.
77 command, shell=True, stderr=subprocess.DEVNULL,
78 stdout=subprocess.DEVNULL, capture_output=False, check=True
82 def cmd_in_background(
83 command: str, *, silent: bool = False
84 ) -> subprocess.Popen:
85 args = shlex.split(command)
87 subproc = subprocess.Popen(args,
88 stdin=subprocess.DEVNULL,
89 stdout=subprocess.DEVNULL,
90 stderr=subprocess.DEVNULL)
92 subproc = subprocess.Popen(args, stdin=subprocess.DEVNULL)
94 def kill_subproc() -> None:
96 if subproc.poll() is None:
97 logger.info("At exit handler: killing {}: {}".format(subproc, command))
99 subproc.wait(timeout=10.0)
100 except BaseException as be:
102 atexit.register(kill_subproc)
106 def cmd_list(command: List[str]) -> str:
107 """Run a command with args encapsulated in a list and return the
108 output text as a string. Raises subprocess.CalledProcessError.
110 ret = subprocess.run(command, capture_output=True, check=True).stdout
111 return ret.decode("utf-8")
114 if __name__ == '__main__':