4
# python-console <port> <magic> [<working-dir>]
14
from threading import Thread
15
from functools import partial
19
class Interrupt(Exception):
21
Exception.__init__(self, "Interrupted!")
23
class ExpiryTimer(object):
24
def __init__(self, idle):
26
signal.signal(signal.SIGALRM, partial(self.timeout))
29
signal.alarm(self.idle)
31
def start(self, time):
37
def timeout(self, signum, frame):
40
class StdinFromWeb(object):
41
def __init__(self, cmdQ, lineQ):
46
self.cmdQ.put({"input":None})
54
class StdoutToWeb(object):
55
def __init__(self, cmdQ, lineQ):
60
def write(self, stuff):
61
# if there's less than 1K, buffer
62
if len(self.remainder) + len(stuff) < 128:
63
self.remainder = self.remainder + stuff
66
# Split the content up into lines, and ship all the completed
67
# lines off to the server.
68
lines = stuff.split("\n")
69
lines[0] = self.remainder + lines[0]
70
self.remainder = lines[-1]
75
text = "\n".join(lines)
76
self.cmdQ.put({"output":text})
83
if len(self.remainder) > 0:
84
self.cmdQ.put({"output":self.remainder})
91
class PythonRunner(Thread):
92
def __init__(self, cmdQ, lineQ):
95
self.stdout = StdoutToWeb(self.cmdQ, self.lineQ)
98
def execCmd(self, cmd):
100
sys.stdin = StdinFromWeb(self.cmdQ, self.lineQ)
101
sys.stdout = self.stdout
102
sys.stderr = self.stdout
103
res = eval(cmd, self.globs, self.locls)
105
self.cmdQ.put({"okay":res})
107
except Exception, exc:
109
self.cmdQ.put({"exc":str(exc)})
114
self.globs['__builtins__'] = globals()['__builtins__']
117
compiler = codeop.CommandCompiler()
120
ln = self.lineQ.get()
122
if self.curr_cmd == '':
123
self.curr_cmd = ln['chat']
125
self.curr_cmd = self.curr_cmd + '\n' + ln['chat']
127
cmd = compiler(self.curr_cmd)
129
# The command was incomplete,
130
# so send back a None, so the
131
# client can print a '...'
132
self.cmdQ.put({"more":None})
135
except Exception, exc:
137
self.cmdQ.put({"exc":str(exc)})
140
# throw away a partial command.
142
cmd = compile(ln['block'], "<web session>", 'exec');
144
except Exception, exc:
146
self.cmdQ.put({"exc":str(exc)})
150
if os.fork(): # launch child and...
151
os._exit(0) # kill off parent
153
if os.fork(): # launch child and...
154
os._exit(0) # kill off parent again.
157
# The global 'magic' is the secret that the client and server share
158
# which is used to create and md5 digest to authenticate requests.
159
# It is assigned a real value at startup.
163
lineQ = Queue.Queue()
164
interpThread = PythonRunner(cmdQ, lineQ)
166
# Default expiry time of 15 minutes
167
expiry = ExpiryTimer(15 * 60)
170
interpThread.setDaemon(True)
174
def dispatch_msg(msg):
176
lineQ.put({msg['cmd']:msg['text']})
179
if __name__ == "__main__":
180
port = int(sys.argv[1])
182
if len(sys.argv) >= 4:
184
os.chdir(sys.argv[3])
186
common.chat.start_server(port, magic, True, dispatch_msg, initializer)