Passed
Pull Request — master (#8)
by
unknown
04:52
created

launch_cmd_displays_output()   A

Complexity

Conditions 5

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
c 0
b 0
f 0
dl 0
loc 15
ccs 10
cts 10
cp 1
crap 5
rs 9.1832
1
"""
2
A command wrapper to get a live output displayed.
3
Useful when you need to write a plugin that outputs some progress or info.
4
"""
5
6 1
import subprocess
7 1
import sys
8 1
from io import BufferedReader
9 1
from click import echo, style
10
11
12 1
def launch_cmd_displays_output(cmd: list, print_msg: bool = True,
13
                               print_err: bool = True, err_to_out: bool = False):
14
    """Launch a command and displays conditionnaly messages and / or errors"""
15
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
    if display is True:
32
        echo(style('[VERBOSE]', fg='green') + ' {}'.format(message), file=sys.stderr)
33
34
35 1
def _read_messages(result: BufferedReader, display: bool = False):
36
    """Print messages sent to the STDOUT"""
37
38 1
    for line in result.stdout:
39 1
        line = line.decode()
40 1
        line = line if display is True else '.'
41 1
        print(line, end='')
42 1
        sys.stdout.flush()
43
44 1
    print()
45
46
47 1
def _print_errors(result: BufferedReader):
48
    """Print messages sent to the STDERR"""
49
50 1
    num = 0
51 1
    for line in result.stderr:
52 1
        err = line.decode()
53
54 1
        if num is 0:
55 1
            print(style("Command returned errors :", fg='red'))
56
57 1
        if num < 5:
58 1
            print(err, end='')
59 1
        elif num is 5:
60 1
            print(style('... and more', fg='red'))
61
62
        num += 1
63