|
1
|
|
|
# coding: utf-8 |
|
2
|
|
|
""" |
|
3
|
|
|
Command Wrapper. |
|
4
|
|
|
|
|
5
|
|
|
A command wrapper to get a live output displayed. |
|
6
|
|
|
""" |
|
7
|
|
|
|
|
8
|
|
|
import subprocess |
|
9
|
|
|
import sys |
|
10
|
|
|
from io import BufferedReader |
|
11
|
|
|
from click import echo, style |
|
12
|
|
|
|
|
13
|
|
|
|
|
14
|
|
|
def launch_cmd_displays_output(cmd: list, print_msg: bool = True, print_err: bool = True, |
|
15
|
|
|
err_to_out: bool = False): |
|
16
|
|
|
"""Launch a command and displays conditionally messages and / or errors.""" |
|
17
|
|
|
try: |
|
18
|
|
|
stderr = subprocess.PIPE if err_to_out is False else subprocess.STDOUT |
|
19
|
|
|
result = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=stderr) |
|
20
|
|
|
except Exception as error: |
|
21
|
|
|
raise SystemError('Cannot run the command: {}'.format(error)) |
|
22
|
|
|
|
|
23
|
|
|
_read_messages(result, print_msg) |
|
24
|
|
|
if print_err is True and err_to_out is False: |
|
25
|
|
|
_print_errors(result) |
|
26
|
|
|
|
|
27
|
|
|
return result |
|
28
|
|
|
|
|
29
|
|
|
|
|
30
|
|
|
def verbose(display: bool, message: str): |
|
31
|
|
|
"""Display a message if verbose is On.""" |
|
32
|
|
|
if display is True: |
|
33
|
|
|
echo(style('[VERBOSE]', fg='green') + ' {}'.format(message), file=sys.stderr) |
|
34
|
|
|
|
|
35
|
|
|
|
|
36
|
|
|
def _read_messages(result: BufferedReader, display: bool = False): |
|
37
|
|
|
"""Print messages sent to the STDOUT.""" |
|
38
|
|
|
for line in result.stdout: |
|
39
|
|
|
line = line.decode() |
|
40
|
|
|
line = line if display is True else '.' |
|
41
|
|
|
print(line, end='') |
|
42
|
|
|
sys.stdout.flush() |
|
43
|
|
|
|
|
44
|
|
|
print() |
|
45
|
|
|
|
|
46
|
|
|
|
|
47
|
|
|
def _print_errors(result: BufferedReader): |
|
48
|
|
|
"""Print messages sent to the STDERR.""" |
|
49
|
|
|
num = 0 |
|
50
|
|
|
for line in result.stderr: |
|
51
|
|
|
err = line.decode() |
|
52
|
|
|
|
|
53
|
|
|
if num == 0: |
|
54
|
|
|
print(style("Command returned errors :", fg='red')) |
|
55
|
|
|
|
|
56
|
|
|
if num < 5: |
|
57
|
|
|
print(err, end='') |
|
58
|
|
|
elif num == 5: |
|
59
|
|
|
print(style('... and more', fg='red')) |
|
60
|
|
|
|
|
61
|
|
|
num += 1 |
|
62
|
|
|
|