-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterpret_test.py
executable file
·63 lines (52 loc) · 1.84 KB
/
interpret_test.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
#!/usr/bin/python
import sys
from cStringIO import StringIO
from code import InteractiveConsole
from contextlib import contextmanager
import socket
import sys, time, select
class MySocket(socket.socket):
def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None):
socket.socket.__init__(self, family, type, proto, _sock)
def write(self, text):
return self.send(text)
def readlines(self):
return self.recv(2048)
def read(self):
return self.recv(1024)
def accept(self):
conn, addr = socket.socket.accept(self)
return MySocket(_sock=conn), addr
@contextmanager
def std_redirector(stdin=sys.stdin, stdout=sys.stdin, stderr=sys.stderr):
tmp_fds = stdin, stdout, stderr
orig_fds = sys.stdin, sys.stdout, sys.stderr
sys.stdin, sys.stdout, sys.stderr = tmp_fds
yield
sys.stdin, sys.stdout, sys.stderr = orig_fds
class Interpreter(InteractiveConsole):
def __init__(self, locals=None, fd=None):
InteractiveConsole.__init__(self, locals=locals)
self.fd = fd
def push(self, command):
with std_redirector(stdin=self.fd, stdout=self.fd, stderr=self.fd):
InteractiveConsole.push(self, command)
if __name__ == '__main__':
import __main__
ns = __main__.__dict__
try:
serversocket = MySocket()
serversocket.bind(("", 12345))
serversocket.listen(1)
conn, addr = serversocket.accept()
py = Interpreter(ns,conn)
py.push('a=1')
py.push('a+=1')
sys.stdin = conn
# print(sys.stdin.read())
while select.select([conn], [], []):
time.sleep(1)
py.push(sys.stdin.read())
except:
import traceback
traceback.print_exc()