Initial revision
[python_utils.git] / exec_utils.py
1 #!/usr/bin/env python3
2
3 import shlex
4 import subprocess
5 from typing import List
6
7
8 def cmd_with_timeout(command: str, timeout_seconds: float) -> int:
9     return subprocess.check_call(
10         ["/bin/bash", "-c", command], timeout=timeout_seconds
11     )
12
13
14 def cmd(command: str) -> str:
15     """Run a command with everything encased in a string and return
16     the output text as a string.  Raises subprocess.CalledProcessError.
17     """
18     ret = subprocess.run(
19         command, shell=True, capture_output=True, check=True
20     ).stdout
21     return ret.decode("utf-8")
22
23
24 def run_silently(command: str) -> None:
25     """Run a command silently but raise subprocess.CalledProcessError if
26     it fails."""
27     subprocess.run(
28         command, shell=True, stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
29         capture_output=False, check=True
30     )
31
32
33 def cmd_in_background(command: str, *, silent: bool = False) -> subprocess.Popen:
34     args = shlex.split(command)
35     if silent:
36         return subprocess.Popen(args,
37                                 stdin=subprocess.DEVNULL,
38                                 stdout=subprocess.DEVNULL,
39                                 stderr=subprocess.DEVNULL)
40     else:
41         return subprocess.Popen(args,
42                                 stdin=subprocess.DEVNULL)
43
44
45 def cmd_list(command: List[str]) -> str:
46     """Run a command with args encapsulated in a list and return the
47     output text as a string.  Raises subprocess.CalledProcessError.
48     """
49     ret = subprocess.run(command, capture_output=True, check=True).stdout
50     return ret.decode("utf-8")