-
Notifications
You must be signed in to change notification settings - Fork 0
/
TermHelper.py
328 lines (273 loc) · 9.51 KB
/
TermHelper.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
import traceback
import threading
import sys
import socket
import select
try:
import readline
except ImportError:
try:
import pyreadline as readline
except ImportError:
readline = None
raise ImportError("Could not import pyreadline")
try:
xrange
except NameError:
xrange = range
def GetLongStrBytes(byts):
"""
:type byts: str
:rtype: int|long
"""
p = 1
rtn = 0
for byt in byts:
rtn += p * ord(byt)
p *= 256
return rtn
def AlignStrBytesLong(l, align):
rtn = ""
while l > 0:
rtn += chr(l % 256)
l /= 256
return rtn + "\0" * (align - len(rtn))
def PackStrLen(s, headlen):
return AlignStrBytesLong(len(s), headlen) + s
class BaseTerm(object):
def PrintLk(self, *args):
raise NotImplementedError("Not Implemented")
def Print(self, *args):
raise NotImplementedError("Not Implemented")
def Write(self, s):
raise NotImplementedError("Not Implemented")
def WriteLk(self, s):
raise NotImplementedError("Not Implemented")
def WriteErr(self, s):
self.Write(s)
def WriteErrLk(self, s):
self.WriteLk(s)
def ReadLine(self, prompt=""):
return ""
def ReadPass(self, prompt=""):
return self.ReadLine(prompt)
def ExitTerm(self):
raise NotImplementedError("Not Implemented")
class CmdTerm(BaseTerm):
def __init__(self):
self.Prompt = None
self.Lk = threading.Lock()
def ReadLine(self, prompt=""):
self.Prompt = prompt
Rtn = input(self.Prompt)
self.Prompt = None
return Rtn
def Write(self, s):
self.PreWrite(s)
sys.stdout.write(s)
self.PostWrite(s)
def WriteLk(self, s):
with self.Lk:
self.Write(s)
def WriteErr(self, s):
self.PreWrite(s)
sys.stderr.write(s)
self.PostWrite(s)
def WriteErrLk(self, s):
with self.Lk:
self.WriteErr(s)
def Print(self, *args):
self.Write(" ".join(map(str, args))+"\n")
def PrintLk(self, *args):
with self.Lk:
self.Print(*args)
def PreWrite(self, str_log):
if self.Prompt is not None:
lenLine = len(readline.get_line_buffer())+len(self.Prompt)
sys.stdout.write("\r"+" "*lenLine+"\r")
def PostWrite(self, str_log):
if self.Prompt is not None:
sys.stdout.write(self.Prompt + readline.get_line_buffer())
sys.stdout.flush()
def LoggerPreW(self, log, c, str_log):
if log.LstFl[c] == sys.stdout:
self.PreWrite(str_log)
def LoggerPostW(self, log, c, str_log):
if log.LstFl[c] == sys.stdout:
self.PostWrite(str_log)
#messages always follow the same format
#when a message is sent a response is expected in order for the action to finish
def MsgSockThrd(SockProt, Step=1, TmOutHandler=None):
while SockProt.IsOpen:
CurTmOut = SockProt.Sock.gettimeout()
while SockProt.IsOpen:
Rtn = None
if CurTmOut is None or Step < CurTmOut:
Rtn = select.select([SockProt.Sock], [], [], Step)[0]
if CurTmOut is not None: CurTmOut -= Step
else:
Rtn = select.select([SockProt.Sock], [], [], CurTmOut)[0]
CurTmOut = 0
if len(Rtn) > 0: break
elif CurTmOut is None: pass
elif CurTmOut == 0:
if TmOutHandler is None or not TmOutHandler(SockProt):
with SockProt.SockLk:
SockProt.IsOpen = False
SockProt.SockCond.notify_all()
break
else: CurTmOut = SockProt.Sock.gettimeout()
if not SockProt.IsOpen: break
Str = SockProt.Sock.recv(1)
if len(Str) == 0:
with SockProt.SockLk:
SockProt.IsOpen = False
SockProt.SockCond.notify_all()
break
#print "RECEIVED %u" % ord(Str)
with SockProt.SockLk:
SockProt.MsgIdRecv = ord(Str)
SockProt.SockCond.notify_all()
SockProt.SockCond.wait()
def ReplShell(terminal, globs, locs, ps1, ps2):
use_locals = True
while True:
# noinspection PyBroadException
try:
inp = terminal.ReadLine(ps1)
inp1 = inp
while inp1.startswith(" ") or inp1.startswith("\t") or inp1.endswith(":"):
inp1 = terminal.ReadLine(ps2)
inp += "\n" + inp1
if len(inp) == 0:
continue
elif inp.startswith("#"):
lower = inp.lower()
str0 = "#use-locals "
str1 = "#exit-cur-repl"
if lower.startswith(str0):
use_locals = int(inp[len(str0):])
elif lower.startswith(str1):
break
output = None
try:
output = eval(inp, globs, locs if use_locals else globs)
except SyntaxError:
exec(inp, globs, locs if use_locals else globs)
if output is not None:
terminal.WriteLk(repr(output))
except:
terminal.WriteErrLk(traceback.format_exc())
def DefReplRunner(inp, globs, locs):
"""
:param str|unicode inp:
:param dict[str|unicode,any] globs:
:param dict[str|unicode,any] locs:
:rtype: (str|unicode, bool)
"""
try:
prn = None
try:
prn = eval(inp, globs, locs)
except SyntaxError:
exec (inp, globs, locs)
if prn is not None:
return repr(prn) + "\n", False
except:
return traceback.format_exc(), True
return "", False
def SockRecvAll(sock, num):
rtn = ""
while num > 0:
data = sock.recv(num)
if len(data) == 0:
raise socket.error("Connection reset by peer")
rtn += data
num -= len(data)
return rtn
class MsgSockProt(object):
def __init__(self, Sock):
self.Sock = Sock
self.SockLk = threading.Lock()
self.MsgIdRecv = None
self.IsOpen = True
self.SockCond = threading.Condition(self.SockLk)
self.SockThrd = threading.Thread(
target=MsgSockThrd, args=(self,),
name="Socket Thread %s" % str(Sock.getpeername()))
self.SockThrd.start()
def SendMsg(self, MsgId, Data, HeadSize=2):
with self.SockLk:
if not self.IsOpen:
raise socket.error("attempted action on closed connection")
self.Sock.sendall(chr(MsgId)+PackStrLen(Data,HeadSize))
while self.MsgIdRecv is None or self.MsgIdRecv != MsgId:
self.SockCond.wait()#wait for the dispatcher thread to recv
if not self.IsOpen: raise socket.error("Connection reset")
self.MsgIdRecv = None
str0 = SockRecvAll(self.Sock, HeadSize)
Len = GetLongStrBytes(str0)
Rtn = SockRecvAll(self.Sock, Len)
self.SockCond.notify_all()#back notify the dispatcher thread
return Rtn
def close(self):
with self.SockLk:
self.IsOpen = False
self.SockThrd.join()
EXIT_TERM = 0
READ_LINE = 1
WRIT_LINE = 2
class SocketTerm(BaseTerm):
def __init__(self):
self.Lks = [threading.Lock(), threading.Lock(), threading.Lock()]
self.SockProt = None
def ReadLine(self, Prompt=""):
with self.Lks[READ_LINE]:
return self.SockProt.SendMsg(READ_LINE, Prompt)
def Write(self, Str):
with self.Lks[WRIT_LINE]:
self.SockProt.SendMsg(WRIT_LINE, Str)
WriteLk = Write
def Print(self, *args):
self.Write(" ".join(map(str, args))+"\n")
PrintLk = Print
def ExitTerm(self):
with self.Lks[EXIT_TERM]:
self.SockProt.SendMsg(EXIT_TERM, "")
class BareSockTerm(SocketTerm):
def __init__(self, Sock):
super(BareSockTerm, self).__init__()
self.SockProt = MsgSockProt(Sock)
def ReplShell1(term_obj, globs, locs, ps1, ps2, fn=DefReplRunner, fn_is_stop=None):
"""
:param fn_is_stop:
:param BaseTerm term_obj:
:param globs:
:param locs:
:param ps1:
:param ps2:
:param (str|unicode,dict[str|unicode,any],dict[str|unicode,any]) -> (str|unicode, bool) fn:
"""
use_locals = True
while True if fn_is_stop is None else not fn_is_stop():
inp = term_obj.ReadLine(ps1)
inp1 = inp
while inp1.startswith(" ") or inp1.startswith("\t") or inp1.endswith(":"):
inp1 = term_obj.ReadLine(ps2)
inp += "\n" + inp1
if len(inp) == 0:
continue
elif inp.startswith("#"):
lower = inp.lower()
str0 = "#use-locals "
str1 = "#exit-cur-repl"
if lower.startswith(str0):
use_locals = int(inp[len(str0):])
continue
elif lower.startswith(str1):
break
prn, is_err = fn(inp, globs, locs if use_locals else globs)
if is_err:
term_obj.WriteErrLk(prn)
else:
term_obj.WriteLk(prn)