summaryrefslogtreecommitdiff
path: root/exec_utils.py
diff options
context:
space:
mode:
authorScott Gasch <[email protected]>2021-03-24 18:08:54 -0700
committerScott Gasch <[email protected]>2021-03-24 18:08:54 -0700
commit497fb9e21f45ec08e1486abaee6dfa7b20b8a691 (patch)
tree47aa97a0fca36c4e7025cee5ad4e9ec6db49b881 /exec_utils.py
Initial revision
Diffstat (limited to 'exec_utils.py')
-rw-r--r--exec_utils.py50
1 files changed, 50 insertions, 0 deletions
diff --git a/exec_utils.py b/exec_utils.py
new file mode 100644
index 0000000..0ed3601
--- /dev/null
+++ b/exec_utils.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python3
+
+import shlex
+import subprocess
+from typing import List
+
+
+def cmd_with_timeout(command: str, timeout_seconds: float) -> int:
+ return subprocess.check_call(
+ ["/bin/bash", "-c", command], timeout=timeout_seconds
+ )
+
+
+def cmd(command: str) -> str:
+ """Run a command with everything encased in a string and return
+ the output text as a string. Raises subprocess.CalledProcessError.
+ """
+ ret = subprocess.run(
+ command, shell=True, capture_output=True, check=True
+ ).stdout
+ return ret.decode("utf-8")
+
+
+def run_silently(command: str) -> None:
+ """Run a command silently but raise subprocess.CalledProcessError if
+ it fails."""
+ subprocess.run(
+ command, shell=True, stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
+ capture_output=False, check=True
+ )
+
+
+def cmd_in_background(command: str, *, silent: bool = False) -> subprocess.Popen:
+ args = shlex.split(command)
+ if silent:
+ return subprocess.Popen(args,
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL)
+ else:
+ return subprocess.Popen(args,
+ stdin=subprocess.DEVNULL)
+
+
+def cmd_list(command: List[str]) -> str:
+ """Run a command with args encapsulated in a list and return the
+ output text as a string. Raises subprocess.CalledProcessError.
+ """
+ ret = subprocess.run(command, capture_output=True, check=True).stdout
+ return ret.decode("utf-8")