-
Notifications
You must be signed in to change notification settings - Fork 60
/
shell.py
60 lines (46 loc) · 1.6 KB
/
shell.py
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
import sys
from subprocess import call, check_output, CalledProcessError
import shouter
logcommands = False
encoding = None
def execute(command, outputfile=None, openmode="w"):
shout_command_to_log(command, outputfile)
if not outputfile:
return call(command, shell=True)
else:
with open(outputfile, openmode, encoding=encoding) as file:
return call(command, stdout=file, shell=True)
def getoutput(command, stripped=True):
shout_command_to_log(command)
try:
outputasbytestring = check_output(command, shell=True)
output = outputasbytestring.decode(sys.stdout.encoding).splitlines()
except CalledProcessError as e:
shouter.shout(e)
output = ""
if not stripped:
return output
else:
lines = []
for line in output:
strippedline = line.strip()
if strippedline:
lines.append(strippedline)
return lines
def quote(stringtoquote):
stringtoquote = stringtoquote.replace('\"', "'") # replace " with '
quotedstring = '\"' + stringtoquote + '\"'
return escapeShellVariableExpansion(quotedstring)
def escapeShellVariableExpansion(comment):
return comment.replace('$', '"\\$"')
def shout_command_to_log(command, outputfile=None):
if logcommands:
logmessage = "Executed Command: " + quote(command)
if outputfile:
shouter.shout(logmessage + " --> " + outputfile)
else:
shouter.shout(logmessage)
def setencoding(encodingtobeset):
global encoding
if encodingtobeset:
encoding = encodingtobeset