Show More
@@ -0,0 +1,270 b'' | |||
|
1 | #!/usr/bin/env python | |
|
2 | """A simple interactive kernel that talks to a frontend over 0MQ. | |
|
3 | ||
|
4 | Things to do: | |
|
5 | ||
|
6 | * Finish implementing `raw_input`. | |
|
7 | * Implement `set_parent` logic. Right before doing exec, the Kernel should | |
|
8 | call set_parent on all the PUB objects with the message about to be executed. | |
|
9 | * Implement random port and security key logic. | |
|
10 | * Implement control messages. | |
|
11 | * Implement event loop and poll version. | |
|
12 | """ | |
|
13 | ||
|
14 | import __builtin__ | |
|
15 | import sys | |
|
16 | import time | |
|
17 | import traceback | |
|
18 | ||
|
19 | from code import CommandCompiler | |
|
20 | ||
|
21 | import zmq | |
|
22 | ||
|
23 | from session import Session, Message, extract_header | |
|
24 | from completer import KernelCompleter | |
|
25 | ||
|
26 | class OutStream(object): | |
|
27 | """A file like object that publishes the stream to a 0MQ PUB socket.""" | |
|
28 | ||
|
29 | def __init__(self, session, pub_socket, name, max_buffer=200): | |
|
30 | self.session = session | |
|
31 | self.pub_socket = pub_socket | |
|
32 | self.name = name | |
|
33 | self._buffer = [] | |
|
34 | self._buffer_len = 0 | |
|
35 | self.max_buffer = max_buffer | |
|
36 | self.parent_header = {} | |
|
37 | ||
|
38 | def set_parent(self, parent): | |
|
39 | self.parent_header = extract_header(parent) | |
|
40 | ||
|
41 | def close(self): | |
|
42 | self.pub_socket = None | |
|
43 | ||
|
44 | def flush(self): | |
|
45 | if self.pub_socket is None: | |
|
46 | raise ValueError(u'I/O operation on closed file') | |
|
47 | else: | |
|
48 | if self._buffer: | |
|
49 | data = ''.join(self._buffer) | |
|
50 | content = {u'name':self.name, u'data':data} | |
|
51 | msg = self.session.msg(u'stream', content=content, | |
|
52 | parent=self.parent_header) | |
|
53 | print>>sys.__stdout__, Message(msg) | |
|
54 | self.pub_socket.send_json(msg) | |
|
55 | self._buffer_len = 0 | |
|
56 | self._buffer = [] | |
|
57 | ||
|
58 | def isattr(self): | |
|
59 | return False | |
|
60 | ||
|
61 | def next(self): | |
|
62 | raise IOError('Read not supported on a write only stream.') | |
|
63 | ||
|
64 | def read(self, size=None): | |
|
65 | raise IOError('Read not supported on a write only stream.') | |
|
66 | ||
|
67 | readline=read | |
|
68 | ||
|
69 | def write(self, s): | |
|
70 | if self.pub_socket is None: | |
|
71 | raise ValueError('I/O operation on closed file') | |
|
72 | else: | |
|
73 | self._buffer.append(s) | |
|
74 | self._buffer_len += len(s) | |
|
75 | self._maybe_send() | |
|
76 | ||
|
77 | def _maybe_send(self): | |
|
78 | if '\n' in self._buffer[-1]: | |
|
79 | self.flush() | |
|
80 | if self._buffer_len > self.max_buffer: | |
|
81 | self.flush() | |
|
82 | ||
|
83 | def writelines(self, sequence): | |
|
84 | if self.pub_socket is None: | |
|
85 | raise ValueError('I/O operation on closed file') | |
|
86 | else: | |
|
87 | for s in sequence: | |
|
88 | self.write(s) | |
|
89 | ||
|
90 | ||
|
91 | class DisplayHook(object): | |
|
92 | ||
|
93 | def __init__(self, session, pub_socket): | |
|
94 | self.session = session | |
|
95 | self.pub_socket = pub_socket | |
|
96 | self.parent_header = {} | |
|
97 | ||
|
98 | def __call__(self, obj): | |
|
99 | if obj is None: | |
|
100 | return | |
|
101 | ||
|
102 | __builtin__._ = obj | |
|
103 | msg = self.session.msg(u'pyout', {u'data':repr(obj)}, | |
|
104 | parent=self.parent_header) | |
|
105 | self.pub_socket.send_json(msg) | |
|
106 | ||
|
107 | def set_parent(self, parent): | |
|
108 | self.parent_header = extract_header(parent) | |
|
109 | ||
|
110 | ||
|
111 | class RawInput(object): | |
|
112 | ||
|
113 | def __init__(self, session, socket): | |
|
114 | self.session = session | |
|
115 | self.socket = socket | |
|
116 | ||
|
117 | def __call__(self, prompt=None): | |
|
118 | msg = self.session.msg(u'raw_input') | |
|
119 | self.socket.send_json(msg) | |
|
120 | while True: | |
|
121 | try: | |
|
122 | reply = self.socket.recv_json(zmq.NOBLOCK) | |
|
123 | except zmq.ZMQError, e: | |
|
124 | if e.errno == zmq.EAGAIN: | |
|
125 | pass | |
|
126 | else: | |
|
127 | raise | |
|
128 | else: | |
|
129 | break | |
|
130 | return reply[u'content'][u'data'] | |
|
131 | ||
|
132 | ||
|
133 | class Kernel(object): | |
|
134 | ||
|
135 | def __init__(self, session, reply_socket, pub_socket): | |
|
136 | self.session = session | |
|
137 | self.reply_socket = reply_socket | |
|
138 | self.pub_socket = pub_socket | |
|
139 | self.user_ns = {} | |
|
140 | self.history = [] | |
|
141 | self.compiler = CommandCompiler() | |
|
142 | self.completer = KernelCompleter(self.user_ns) | |
|
143 | ||
|
144 | # Build dict of handlers for message types | |
|
145 | self.handlers = {} | |
|
146 | for msg_type in ['execute_request', 'complete_request']: | |
|
147 | self.handlers[msg_type] = getattr(self, msg_type) | |
|
148 | ||
|
149 | def abort_queue(self): | |
|
150 | while True: | |
|
151 | try: | |
|
152 | ident = self.reply_socket.recv(zmq.NOBLOCK) | |
|
153 | except zmq.ZMQError, e: | |
|
154 | if e.errno == zmq.EAGAIN: | |
|
155 | break | |
|
156 | else: | |
|
157 | assert self.reply_socket.rcvmore(), "Unexpected missing message part." | |
|
158 | msg = self.reply_socket.recv_json() | |
|
159 | print>>sys.__stdout__, "Aborting:" | |
|
160 | print>>sys.__stdout__, Message(msg) | |
|
161 | msg_type = msg['msg_type'] | |
|
162 | reply_type = msg_type.split('_')[0] + '_reply' | |
|
163 | reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg) | |
|
164 | print>>sys.__stdout__, Message(reply_msg) | |
|
165 | self.reply_socket.send(ident,zmq.SNDMORE) | |
|
166 | self.reply_socket.send_json(reply_msg) | |
|
167 | # We need to wait a bit for requests to come in. This can probably | |
|
168 | # be set shorter for true asynchronous clients. | |
|
169 | time.sleep(0.1) | |
|
170 | ||
|
171 | def execute_request(self, ident, parent): | |
|
172 | try: | |
|
173 | code = parent[u'content'][u'code'] | |
|
174 | except: | |
|
175 | print>>sys.__stderr__, "Got bad msg: " | |
|
176 | print>>sys.__stderr__, Message(parent) | |
|
177 | return | |
|
178 | pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent) | |
|
179 | self.pub_socket.send_json(pyin_msg) | |
|
180 | try: | |
|
181 | comp_code = self.compiler(code, '<zmq-kernel>') | |
|
182 | sys.displayhook.set_parent(parent) | |
|
183 | exec comp_code in self.user_ns, self.user_ns | |
|
184 | except: | |
|
185 | result = u'error' | |
|
186 | etype, evalue, tb = sys.exc_info() | |
|
187 | tb = traceback.format_exception(etype, evalue, tb) | |
|
188 | exc_content = { | |
|
189 | u'status' : u'error', | |
|
190 | u'traceback' : tb, | |
|
191 | u'etype' : unicode(etype), | |
|
192 | u'evalue' : unicode(evalue) | |
|
193 | } | |
|
194 | exc_msg = self.session.msg(u'pyerr', exc_content, parent) | |
|
195 | self.pub_socket.send_json(exc_msg) | |
|
196 | reply_content = exc_content | |
|
197 | else: | |
|
198 | reply_content = {'status' : 'ok'} | |
|
199 | reply_msg = self.session.msg(u'execute_reply', reply_content, parent) | |
|
200 | print>>sys.__stdout__, Message(reply_msg) | |
|
201 | self.reply_socket.send(ident, zmq.SNDMORE) | |
|
202 | self.reply_socket.send_json(reply_msg) | |
|
203 | if reply_msg['content']['status'] == u'error': | |
|
204 | self.abort_queue() | |
|
205 | ||
|
206 | def complete_request(self, ident, parent): | |
|
207 | matches = {'matches' : self.complete(parent), | |
|
208 | 'status' : 'ok'} | |
|
209 | completion_msg = self.session.send(self.reply_socket, 'complete_reply', | |
|
210 | matches, parent, ident) | |
|
211 | print >> sys.__stdout__, completion_msg | |
|
212 | ||
|
213 | def complete(self, msg): | |
|
214 | return self.completer.complete(msg.content.line, msg.content.text) | |
|
215 | ||
|
216 | def start(self): | |
|
217 | while True: | |
|
218 | ident = self.reply_socket.recv() | |
|
219 | assert self.reply_socket.rcvmore(), "Unexpected missing message part." | |
|
220 | msg = self.reply_socket.recv_json() | |
|
221 | omsg = Message(msg) | |
|
222 | print>>sys.__stdout__, omsg | |
|
223 | handler = self.handlers.get(omsg.msg_type, None) | |
|
224 | if handler is None: | |
|
225 | print >> sys.__stderr__, "UNKNOWN MESSAGE TYPE:", omsg | |
|
226 | else: | |
|
227 | handler(ident, omsg) | |
|
228 | ||
|
229 | ||
|
230 | def main(): | |
|
231 | c = zmq.Context() | |
|
232 | ||
|
233 | ip = '127.0.0.1' | |
|
234 | port_base = 5575 | |
|
235 | connection = ('tcp://%s' % ip) + ':%i' | |
|
236 | rep_conn = connection % port_base | |
|
237 | pub_conn = connection % (port_base+1) | |
|
238 | ||
|
239 | print >>sys.__stdout__, "Starting the kernel..." | |
|
240 | print >>sys.__stdout__, "On:",rep_conn, pub_conn | |
|
241 | ||
|
242 | session = Session(username=u'kernel') | |
|
243 | ||
|
244 | reply_socket = c.socket(zmq.XREP) | |
|
245 | reply_socket.bind(rep_conn) | |
|
246 | ||
|
247 | pub_socket = c.socket(zmq.PUB) | |
|
248 | pub_socket.bind(pub_conn) | |
|
249 | ||
|
250 | stdout = OutStream(session, pub_socket, u'stdout') | |
|
251 | stderr = OutStream(session, pub_socket, u'stderr') | |
|
252 | sys.stdout = stdout | |
|
253 | sys.stderr = stderr | |
|
254 | ||
|
255 | display_hook = DisplayHook(session, pub_socket) | |
|
256 | sys.displayhook = display_hook | |
|
257 | ||
|
258 | kernel = Kernel(session, reply_socket, pub_socket) | |
|
259 | ||
|
260 | # For debugging convenience, put sleep and a string in the namespace, so we | |
|
261 | # have them every time we start. | |
|
262 | kernel.user_ns['sleep'] = time.sleep | |
|
263 | kernel.user_ns['s'] = 'Test string' | |
|
264 | ||
|
265 | print >>sys.__stdout__, "Use Ctrl-\\ (NOT Ctrl-C!) to terminate." | |
|
266 | kernel.start() | |
|
267 | ||
|
268 | ||
|
269 | if __name__ == '__main__': | |
|
270 | main() |
General Comments 0
You need to be logged in to leave comments.
Login now