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