-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathshell_commands.py
More file actions
60 lines (46 loc) · 1.87 KB
/
Copy pathshell_commands.py
File metadata and controls
60 lines (46 loc) · 1.87 KB
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
51
52
53
54
55
56
57
58
59
60
import subprocess
from pathlib import Path
from typing import Any, Iterable, Union
ShellCommand = Iterable[Union[str, Path]]
SHOW_COMMANDS = False
def set_show_commands(val: bool):
global SHOW_COMMANDS
SHOW_COMMANDS = val
def run_shell_command(
cmd: ShellCommand, *, quiet: bool, check: bool = True, **kwargs: Any
) -> subprocess.CompletedProcess:
"""Runs a shell command using the arguments provided.
This is essentially a wrapper around subprocess.run, with more reasonable
default arguments, and some debug logging.
Args:
cmd: shell command to run.
check: see subprocess.run for semantics.
**kwargs: see subprocess.run for semantics
(https://docs.python.org/3/library/subprocess.html#subprocess.run).
Returns:
A subprocess.CompletedProcess object.
"""
if "shell" in kwargs:
raise ValueError("shell support has been removed")
_ = subprocess.list2cmdline(cmd)
kwargs.update({"check": check})
if quiet:
kwargs.update({"stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL})
if SHOW_COMMANDS:
print(f"Running: {cmd}")
return subprocess.run(list(map(str, cmd)), **kwargs)
def get_command_output(cmd: ShellCommand, **kwargs: Any) -> str:
"""A wrapper over run_shell_command that captures stdout into a string.
Args:
cmd: shell command to run.
**kwargs: see run_shell_command for semantics. Passing capture_output is
not allowed.
Returns:
Captured stdout of the command as a string.
Raises:
ValueError: if the capture_output keyword argument is specified.
"""
if "capture_output" in kwargs:
raise ValueError("Cannot pass capture_output when using get_command_output")
proc = run_shell_command(cmd, capture_output=True, quiet=False, **kwargs)
return proc.stdout.decode("utf-8").rstrip()