4
# python-console <port> <magic>
15
from threading import Thread
19
class ExpiryTimer(object):
20
def __init__(self, idle):
22
signal.signal(signal.SIGALRM, partial(self.timeout,self))
25
signal.alarm(self.idle)
27
def start(self, time):
33
def timeout(self, signum, frame):
36
class StdinFromWeb(object):
37
def __init__(self, cmdQ, lineQ):
43
self.cmdQ.put({"input":None})
49
class PythonRunner(Thread):
50
def __init__(self, cmdQ, lineQ):
53
self.out = cStringIO.StringIO()
56
def execCmd(self, cmd):
58
sys.stdin = StdinFromWeb(self.cmdQ, self.lineQ)
61
res = eval(cmd, self.globs, self.locls)
62
self.cmdQ.put({"okay":(self.out.getvalue(),res)})
64
self.out = cStringIO.StringIO()
65
except Exception, exc:
66
self.cmdQ.put({"exc":(self.out.getvalue(),str(exc))})
68
self.out = cStringIO.StringIO()
72
compiler = codeop.CommandCompiler()
77
if self.curr_cmd == '':
78
self.curr_cmd = ln['chat']
80
self.curr_cmd = self.curr_cmd + '\n' + ln['chat']
82
cmd = compiler(self.curr_cmd)
84
# The command was incomplete,
85
# so send back a None, so the
86
# client can print a '...'
87
self.cmdQ.put({"more":None})
90
except Exception, exc:
91
self.cmdQ.put({"exc":(self.out.getvalue(),str(exc))})
93
self.out = cStringIO.StringIO()
95
# throw away a partial command.
97
cmd = compile(ln['block'], "<web session>", 'exec');
99
except Exception, exc:
100
self.cmdQ.put({"exc":(self.out.getvalue(),str(exc))})
102
self.out = cStringIO.StringIO()
104
def init_state(self):
106
self.globs['__builtins__'] = globals()['__builtins__']
111
if os.fork(): # launch child and...
112
os._exit(0) # kill off parent
114
if os.fork(): # launch child and...
115
os._exit(0) # kill off parent again.
118
# The global 'magic' is the secret that the client and server share
119
# which is used to create and md5 digest to authenticate requests.
120
# It is assigned a real value at startup.
124
lineQ = Queue.Queue()
125
interpThread = PythonRunner(cmdQ, lineQ)
127
# Default expiry time of 15 minutes
128
expiry = ExpiryTimer(15 * 60)
131
interpThread.setDaemon(True)
135
def dispatch_msg(msg):
137
lineQ.put({msg['cmd']:msg['text']})
140
if __name__ == "__main__":
141
port = int(sys.argv[1])
144
common.chat.start_server(port, magic, True, dispatch_msg, initializer)