1 | import os |
||
2 | from subprocess import Popen, PIPE |
||
3 | |||
4 | |||
5 | View Code Duplication | class SystemCommand: |
|
0 ignored issues
–
show
Duplication
introduced
by
![]() |
|||
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 |