-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmd.py
More file actions
50 lines (43 loc) · 994 Bytes
/
cmd.py
File metadata and controls
50 lines (43 loc) · 994 Bytes
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
import subprocess
import json
class Cmd:
"""
Simple subprocess wrapper to provide convenience methods for common interactions.
"""
def __init__(self, cmd: list):
self.cmd = cmd
self.result = None
def exists(self) -> bool:
"""
Check if this binary exists
:return:
"""
return subprocess.run(['which', self.cmd[0]], check=False, stdout=subprocess.PIPE).returncode == 0
def text(self) -> str:
"""
Get the output of the command as raw text
:return:
"""
return self._exec().stdout.strip()
def lines(self) -> list:
"""
Get the output of the command as lines of text (as a list)
:return:
"""
return self.text().split('\n')
def json(self):
"""
Get the output of the command decoded as JSON
:return:
"""
return json.loads(self.text())
def _exec(self):
if self.result is None:
self.result = subprocess.run(
self.cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True,
encoding='utf-8'
)
return self.result