dirutility.system   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 64
Duplicated Lines 90.63 %

Importance

Changes 0
Metric Value
eloc 32
dl 58
loc 64
rs 10
c 0
b 0
f 0
wmc 11

8 Methods

Rating   Name   Duplication   Size   Complexity  
A SystemCommand.__iter__() 2 2 1
A SystemCommand.success() 4 4 1
A SystemCommand.execute() 11 12 3
A SystemCommand.__getitem__() 2 2 1
A SystemCommand.__init__() 22 22 2
A SystemCommand.__str__() 2 2 1
A SystemCommand.output() 4 4 1
A SystemCommand.__len__() 2 2 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
import os
2
from subprocess import Popen, PIPE
3
4
5 View Code Duplication
class SystemCommand:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
6
7
    def __init__(self, command, decode_output=True, immediate_execution=True):
8
        """
9
        Execute a system command.
10
11
        When decode_output is True, console output is captured, decoded
12
        and returned in list a list of strings.
13
14
        :param command: Command to execute
15
        :param decode_output: Optionally capture and decode console output
16
        :param immediate_execution: Execute system command during initialization
17
        :return: List of output strings
18
        """
19
        # Parameter attributes
20
        self.command = command
21
        self._decode_output = decode_output
22
23
        # Private attributes
24
        self._output, self._success = None, False
25
26
        # Execute command
27
        if immediate_execution:
28
            self.execute()
29
30
    def __str__(self):
31
        return self.command
32
33
    def __iter__(self):
34
        return iter(self._output)
35
36
    def __getitem__(self, item):
37
        return self._output[item]
38
39
    def __len__(self):
40
        return len(self._output)
41
42
    @property
43
    def output(self):
44
        """Return the standard output produced by execution of the system command."""
45
        return self._output
46
47
    @property
48
    def success(self):
49
        """Return a boolean stating weather the command has been successfully executed."""
50
        return self._success
51
52
    def execute(self):
53
        """Execute a system command."""
54
        if self._decode_output:
55
            # Capture and decode system output
56
            with Popen(self.command, shell=True, stdout=PIPE) as process:
57
                self._output = [i.decode("utf-8").strip() for i in process.stdout]
58
                self._success = True
59
        else:
60
            # Execute without capturing output
61
            os.system(self.command)
62
            self._success = True
63
        return self
64