Random changes.
[python_utils.git] / exec_utils.py
1 #!/usr/bin/env python3
2
3 import shlex
4 import subprocess
5 from typing import List, Optional
6
7
8 def cmd_with_timeout(command: str, timeout_seconds: Optional[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,
29         stdout=subprocess.DEVNULL, capture_output=False, check=True
30     )
31
32
33 def cmd_in_background(
34         command: str, *, silent: bool = False
35 ) -> subprocess.Popen:
36     args = shlex.split(command)
37     if silent:
38         return subprocess.Popen(args,
39                                 stdin=subprocess.DEVNULL,
40                                 stdout=subprocess.DEVNULL,
41                                 stderr=subprocess.DEVNULL)
42     else:
43         return subprocess.Popen(args,
44                                 stdin=subprocess.DEVNULL)
45
46
47 def cmd_list(command: List[str]) -> str:
48     """Run a command with args encapsulated in a list and return the
49     output text as a string.  Raises subprocess.CalledProcessError.
50     """
51     ret = subprocess.run(command, capture_output=True, check=True).stdout
52     return ret.decode("utf-8")