This repository was archived by the owner on Mar 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathCommand.py
208 lines (173 loc) · 7.88 KB
/
Command.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
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import os
import signal
import subprocess
import time
import logging
from threading import Thread, Timer
logger = logging.getLogger(__name__)
class Command(object):
timeout = 15
def __init__(self, args, env, callback, query=None, encoding='utf-8',
options=None, timeout=15, silenceErrors=False, stream=False):
if options is None:
options = {}
self.args = args
self.env = env
self.callback = callback
self.query = query
self.encoding = encoding
self.options = options
self.timeout = timeout
self.silenceErrors = silenceErrors
self.stream = stream
self.process = None
if 'show_query' not in self.options:
self.options['show_query'] = False
elif self.options['show_query'] not in ['top', 'bottom']:
self.options['show_query'] = 'top' if (isinstance(self.options['show_query'], bool) and
self.options['show_query']) else False
def run(self):
if not self.query:
return
self.args = map(str, self.args)
si = None
if os.name == 'nt':
si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# select appropriate file handle for stderr
# usually we want to redirect stderr to stdout, so erros are shown
# in the output in the right place (where they actually occurred)
# only if silenceErrors=True, we separate stderr from stdout and discard it
stderrHandle = subprocess.STDOUT
if self.silenceErrors:
stderrHandle = subprocess.PIPE
# set the environment
modifiedEnvironment = os.environ.copy()
if (self.env):
modifiedEnvironment.update(self.env)
queryTimerStart = time.time()
self.process = subprocess.Popen(self.args,
stdout=subprocess.PIPE,
stderr=stderrHandle,
stdin=subprocess.PIPE,
env=modifiedEnvironment,
startupinfo=si)
if self.stream:
self.process.stdin.write(self.query.encode(self.encoding))
self.process.stdin.close()
hasWritten = False
for line in self.process.stdout:
self.callback(line.decode(self.encoding, 'replace').replace('\r', ''))
hasWritten = True
queryTimerEnd = time.time()
# we are done with the output, terminate the process
if self.process:
self.process.terminate()
else:
if hasWritten:
self.callback('\n')
if self.options['show_query']:
formattedQueryInfo = self._formatShowQuery(self.query, queryTimerStart, queryTimerEnd)
self.callback(formattedQueryInfo + '\n')
return
# regular mode is handled with more reliable Popen.communicate
# which also terminates the process afterwards
results, errors = self.process.communicate(input=self.query.encode(self.encoding))
queryTimerEnd = time.time()
resultString = ''
if results:
resultString += results.decode(self.encoding,
'replace').replace('\r', '')
if errors and not self.silenceErrors:
resultString += errors.decode(self.encoding,
'replace').replace('\r', '')
if self.process is None and resultString != '':
resultString += '\n'
if self.options['show_query']:
formattedQueryInfo = self._formatShowQuery(self.query, queryTimerStart, queryTimerEnd)
queryPlacement = self.options['show_query']
if queryPlacement == 'top':
resultString = "{0}\n{1}".format(formattedQueryInfo, resultString)
elif queryPlacement == 'bottom':
resultString = "{0}{1}\n".format(resultString, formattedQueryInfo)
self.callback(resultString)
@staticmethod
def _formatShowQuery(query, queryTimeStart, queryTimeEnd):
resultInfo = "/*\n-- Executed querie(s) at {0} took {1:.3f} s --".format(
str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(queryTimeStart))),
(queryTimeEnd - queryTimeStart))
resultLine = "-" * (len(resultInfo) - 3)
resultString = "{0}\n{1}\n{2}\n{3}\n*/".format(
resultInfo, resultLine, query, resultLine)
return resultString
@staticmethod
def createAndRun(args, env, callback, query=None, encoding='utf-8',
options=None, timeout=15, silenceErrors=False, stream=False):
if options is None:
options = {}
command = Command(args=args,
env=env,
callback=callback,
query=query,
encoding=encoding,
options=options,
timeout=timeout,
silenceErrors=silenceErrors,
stream=stream)
command.run()
class ThreadCommand(Command, Thread):
def __init__(self, args, env, callback, query=None, encoding='utf-8',
options=None, timeout=Command.timeout, silenceErrors=False, stream=False):
if options is None:
options = {}
Command.__init__(self,
args=args,
env=env,
callback=callback,
query=query,
encoding=encoding,
options=options,
timeout=timeout,
silenceErrors=silenceErrors,
stream=stream)
Thread.__init__(self)
def stop(self):
if not self.process:
return
# if poll returns None - proc still running, otherwise returns process return code
if self.process.poll() is not None:
return
try:
# Windows does not provide SIGKILL, go with SIGTERM
sig = getattr(signal, 'SIGKILL', signal.SIGTERM)
os.kill(self.process.pid, sig)
self.process = None
logger.info("command execution exceeded timeout (%s s), process killed", self.timeout)
self.callback(("Command execution time exceeded 'thread_timeout' ({0} s).\n"
"Process killed!\n\n"
).format(self.timeout))
except Exception:
logger.info("command execution exceeded timeout (%s s), process could not be killed", self.timeout)
self.callback(("Command execution time exceeded 'thread_timeout' ({0} s).\n"
"Process could not be killed!\n\n"
).format(self.timeout))
pass
@staticmethod
def createAndRun(args, env, callback, query=None, encoding='utf-8',
options=None, timeout=Command.timeout, silenceErrors=False, stream=False):
# Don't allow empty dicts or lists as defaults in method signature,
# cfr http://nedbatchelder.com/blog/200806/pylint.html
if options is None:
options = {}
command = ThreadCommand(args=args,
env=env,
callback=callback,
query=query,
encoding=encoding,
options=options,
timeout=timeout,
silenceErrors=silenceErrors,
stream=stream)
command.start()
killTimeout = Timer(command.timeout, command.stop)
killTimeout.start()