-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasicterminal.py
More file actions
125 lines (91 loc) · 2.05 KB
/
basicterminal.py
File metadata and controls
125 lines (91 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import sys
import subprocess
logging = False
# LOGGING
def set_logging(state):
logging = state
# TERMINAL
def get_first_argument():
arg = ''
try:
arg = sys.argv[1]
except:
arg = ''
return arg
def get_second_argument():
arg = ''
try:
arg = sys.argv[2]
except:
arg = ''
return arg
def get_all_arguments():
if len(sys.argv) > 1:
return sys.argv[1:]
return []
def handle_argument(arg, trigger='-'):
if trigger in arg and trigger == '-':
# do something different here
print('{} '.format(arg), end='')
else:
print('{} '.format(arg), end='')
def cli(cmd, printErrors=True):
if logging:
print('opening ' + cmd[0], end=': ')
[handle_argument(arg) for arg in cmd[1:]]
output = run_with_popen(cmd)
if not printErrors:
output = validate_output(output)
return output
def run_with_popen(command):
if logging: print('waiting for response from subprocess')
out = ''
err = ''
output = subprocess.Popen(command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = output.communicate()
if err:
return str(err)
else:
return out
def run_and_get_output(cmd):
if logging: print('waiting for response from subprocess')
cmd = list_to_str(cmd)
try:
output = subprocess.check_output(cmd,
shell=True,
stderr=subprocess.STDOUT) \
.decode("utf-8") \
.strip()
except:
output = ''
return output
# OUTPUT
def validate_output(output):
'''
Checks for known problems
Args:
output (str): this is expected to be the string output returned by
subprocess
Returns:
None: where a problem is identified, None is returned
Str: where no problems are identified, the argument is returned
'''
bin_sh = '/bin/sh'
not_found = 'not found'
if type(output) != type(''):
output = str(output)
if bin_sh in output and not_found in output:
return None
return output
# CONVERTERS
def list_to_str(obj):
if type(obj) == type([]):
obj = ' '.join(obj)
return obj
def str_to_list(obj):
if type(obj) == type(''):
obj = obj.split(' ')
return obj