summaryrefslogtreecommitdiff
path: root/exec_utils.py
blob: 0ed360191d6ad9f89c64acf591f78044008f4009 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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")