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})
52
class StdoutToWeb(object):
53
def __init__(self, cmdQ, lineQ):
58
def write(self, stuff):
59
# Split the content up into lines, and ship all the completed
60
# lines off to the server.
61
lines = stuff.split("\n")
62
lines[0] = self.remainder + lines[0]
63
self.remainder = lines[-1]
68
text = "\n".join(lines)
69
self.cmdQ.put({"output":text})
76
if len(self.remainder) > 0:
77
self.cmdQ.put({"output":self.remainder})
84
class PythonRunner(Thread):
85
def __init__(self, cmdQ, lineQ):
91
def execCmd(self, cmd):
93
sys.stdin = StdinFromWeb(self.cmdQ, self.lineQ)
94
self.stdout = StdoutToWeb(self.cmdQ, self.lineQ)
95
sys.stdout = self.stdout
96
sys.stderr = self.stdout
97
res = eval(cmd, self.globs, self.locls)
99
self.cmdQ.put({"okay":res})
101
except Exception, exc:
103
self.cmdQ.put({"exc":str(exc)})
108
self.globs['__builtins__'] = globals()['__builtins__']
111
compiler = codeop.CommandCompiler()
114
ln = self.lineQ.get()
116
if self.curr_cmd == '':
117
self.curr_cmd = ln['chat']
119
self.curr_cmd = self.curr_cmd + '\n' + ln['chat']
121
cmd = compiler(self.curr_cmd)
123
# The command was incomplete,
124
# so send back a None, so the
125
# client can print a '...'
126
self.cmdQ.put({"more":None})
129
except Exception, exc:
131
self.cmdQ.put({"exc":str(exc)})
134
# throw away a partial command.
136
cmd = compile(ln['block'], "<web session>", 'exec');
138
except Exception, exc:
140
self.cmdQ.put({"exc":str(exc)})
144
if os.fork(): # launch child and...
145
os._exit(0) # kill off parent
147
if os.fork(): # launch child and...
148
os._exit(0) # kill off parent again.
151
# The global 'magic' is the secret that the client and server share
152
# which is used to create and md5 digest to authenticate requests.
153
# It is assigned a real value at startup.
157
lineQ = Queue.Queue()
158
interpThread = PythonRunner(cmdQ, lineQ)
160
# Default expiry time of 15 minutes
161
expiry = ExpiryTimer(15 * 60)
164
interpThread.setDaemon(True)
168
def dispatch_msg(msg):
170
lineQ.put({msg['cmd']:msg['text']})
173
if __name__ == "__main__":
174
port = int(sys.argv[1])
176
if len(sys.argv) >= 4:
178
os.chdir(sys.argv[3])
180
common.chat.start_server(port, magic, True, dispatch_msg, initializer)