Show More
@@ -1,270 +1,284 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Frontend of ipython working with python-zmq |
|
3 | 3 | |
|
4 | 4 | Ipython's frontend, is a ipython interface that send request to kernel and proccess the kernel's outputs. |
|
5 | 5 | |
|
6 | 6 | For more details, see the ipython-zmq design |
|
7 | 7 | """ |
|
8 | 8 | #----------------------------------------------------------------------------- |
|
9 | 9 | # Copyright (C) 2010 The IPython Development Team |
|
10 | 10 | # |
|
11 | 11 | # Distributed under the terms of the BSD License. The full license is in |
|
12 | 12 | # the file COPYING, distributed as part of this software. |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | # Imports |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 18 | |
|
19 | 19 | import __builtin__ |
|
20 | 20 | from contextlib import nested |
|
21 | 21 | import time |
|
22 | 22 | import sys |
|
23 | 23 | import os |
|
24 | 24 | import signal |
|
25 | 25 | import uuid |
|
26 | 26 | import cPickle as pickle |
|
27 | 27 | import code |
|
28 | 28 | import zmq |
|
29 | 29 | import rlcompleter |
|
30 | import readline | |
|
30 | 31 | import time |
|
31 | 32 | |
|
32 | 33 | |
|
33 | 34 | #----------------------------------------------------------------------------- |
|
34 | 35 | # Imports from ipython |
|
35 | 36 | #----------------------------------------------------------------------------- |
|
36 | 37 | from IPython.external.argparse import ArgumentParser |
|
37 | 38 | from IPython.utils.traitlets import ( |
|
38 | 39 | Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode |
|
39 | 40 | ) |
|
40 | 41 | from IPython.core.interactiveshell import get_default_colors |
|
41 | 42 | from IPython.core.excolors import exception_colors |
|
42 | 43 | from IPython.utils import PyColorize |
|
43 | 44 | from IPython.core.inputsplitter import InputSplitter |
|
44 | 45 | from IPython.frontend.terminal.kernelmanager import KernelManager2p as KernelManager |
|
45 | 46 | from IPython.zmq.session import Session |
|
46 | 47 | from IPython.zmq import completer |
|
47 | 48 | #----------------------------------------------------------------------------- |
|
48 | 49 | # Network Constants |
|
49 | 50 | #----------------------------------------------------------------------------- |
|
50 | 51 | |
|
51 | 52 | from IPython.utils.localinterfaces import LOCALHOST, LOCAL_IPS |
|
52 | 53 | class Frontend(object): |
|
53 | 54 | """ this class is a simple frontend to ipython-zmq |
|
54 | 55 | |
|
55 | 56 | NOTE: this class use kernelmanager to manipulate sockets |
|
56 | 57 | |
|
57 | 58 | Parameters: |
|
58 | 59 | ----------- |
|
59 | 60 | kernelmanager : object |
|
60 | 61 | instantiated object from class KernelManager in module kernelmanager |
|
61 | 62 | |
|
62 | 63 | """ |
|
63 | 64 | |
|
64 | 65 | def __init__(self,kernelmanager): |
|
65 | 66 | self.km = kernelmanager |
|
66 | 67 | self.session = kernelmanager.session |
|
67 | 68 | self.request_socket = self.km.xreq_channel.socket |
|
68 | 69 | self.sub_socket = self.km.sub_channel.socket |
|
69 | 70 | self.reply_socket = self.km.rep_channel.socket |
|
70 | 71 | self.msg_header = self.km.session.msg_header() |
|
71 | 72 | |
|
72 | 73 | self.completer = completer.ClientCompleter(self,self.session,self.request_socket) |
|
73 |
|
|
|
74 |
|
|
|
75 |
|
|
|
74 | readline.set_completer(self.completer.complete) | |
|
75 | readline.parse_and_bind("tab: complete") | |
|
76 | readline.parse_and_bind('set show-all-if-ambiguous on') | |
|
76 | 77 | |
|
77 | 78 | history_path = os.path.expanduser('~/.ipython/history') |
|
78 | 79 | if os.path.isfile(history_path): |
|
79 | 80 | rlcompleter.readline.read_history_file(history_path) |
|
80 | 81 | else: |
|
81 | 82 | print("history file can not be readed.") |
|
82 | 83 | |
|
83 | 84 | self.messages = {} |
|
84 | 85 | |
|
85 | 86 | self.prompt_count = 0 #self.km.xreq_channel.execute('', silent=True) |
|
86 | 87 | self.backgrounded = 0 |
|
87 | 88 | self._splitter = InputSplitter() |
|
88 | 89 | self.code = "" |
|
89 | 90 | |
|
90 | 91 | def interact(self): |
|
91 | 92 | """ let you get input from console using inputsplitter, then |
|
92 | 93 | while you enter code it can indent and set index id to any input |
|
93 | 94 | |
|
94 | 95 | """ |
|
95 | 96 | |
|
96 | 97 | try: |
|
97 | 98 | self._splitter.push(raw_input('In[%i]:'%self.prompt_count+self.code)) |
|
98 | 99 | while self._splitter.push_accepts_more(): |
|
99 | 100 | self.code = raw_input('.....:'+' '*self._splitter.indent_spaces) |
|
100 | 101 | self._splitter.push(' '*self._splitter.indent_spaces+self.code) |
|
101 | 102 | self._execute(self._splitter.source,False) |
|
102 | 103 | self._splitter.reset() |
|
103 | 104 | except KeyboardInterrupt: |
|
104 | 105 | print('\nKeyboardInterrupt\n') |
|
105 | 106 | pass |
|
106 | 107 | #else: |
|
107 | 108 | #self._execute(self._splitter.source,False) |
|
108 | 109 | #self._splitter.reset() |
|
109 | 110 | |
|
110 | 111 | |
|
111 | 112 | def start(self): |
|
112 | 113 | """ init a bucle that call interact method to get code. |
|
113 | 114 | |
|
114 | 115 | """ |
|
115 | 116 | while True: |
|
116 | 117 | try: |
|
117 | 118 | self.interact() |
|
118 | 119 | except KeyboardInterrupt: |
|
119 | 120 | print('\nKeyboardInterrupt\n') |
|
120 | 121 | pass |
|
121 | 122 | except EOFError: |
|
122 | 123 | answer = '' |
|
123 | 124 | while True: |
|
124 | 125 | answer = raw_input('\nDo you really want to exit ([y]/n)?') |
|
125 | 126 | if answer == 'y' or answer == '' : |
|
126 | 127 | self.km.shutdown_kernel() |
|
127 | 128 | sys.exit() |
|
128 | 129 | elif answer == 'n': |
|
129 | 130 | break |
|
130 | 131 | def _execute(self, source, hidden = True): |
|
131 | 132 | """ Execute 'source'. If 'hidden', do not show any output. |
|
132 | 133 | |
|
133 | 134 | See parent class :meth:`execute` docstring for full details. |
|
134 | 135 | """ |
|
135 | 136 | self.km.xreq_channel.execute(source, hidden) |
|
136 | 137 | self.handle_xreq_channel() |
|
138 | self.handle_rep_channel() | |
|
137 | 139 | |
|
138 | 140 | def handle_xreq_channel(self): |
|
139 | 141 | # Give the kernel up to 0.5s to respond |
|
140 | 142 | for i in range(5): |
|
141 | 143 | if self.km.xreq_channel.was_called(): |
|
142 | 144 | self.msg_xreq = self.km.xreq_channel.get_msg() |
|
145 | #print self.msg_xreq | |
|
143 | 146 | if self.msg_header["session"] == self.msg_xreq["parent_header"]["session"] : |
|
144 | 147 | if self.msg_xreq["content"]["status"] == 'ok' : |
|
145 | 148 | if self.msg_xreq["msg_type"] == "complete_reply" : |
|
146 | 149 | print self.msg_xreq["content"]["matches"] |
|
147 | 150 | |
|
148 | 151 | if self.msg_xreq["msg_type"] == "execute_reply" : |
|
149 | 152 | self.handle_sub_channel() |
|
150 | 153 | self.prompt_count = self.msg_xreq["content"]["execution_count"] |
|
151 | 154 | |
|
152 | 155 | else: |
|
153 | 156 | print >> sys.stderr, "Error executing: ",self.msg_xreq ##traceback no implemented yet here |
|
154 | 157 | print >> sys.stderr, "Status in the kernel: ", self.msg_xreq["content"]["status"] |
|
155 | 158 | break |
|
156 | 159 | time.sleep(0.1) |
|
157 | 160 | |
|
158 | 161 | |
|
159 | 162 | |
|
160 | 163 | def handle_sub_channel(self): |
|
161 | 164 | """ Method to procces subscribe channel's messages |
|
162 | 165 | |
|
163 | 166 | this method read a message and procces the content |
|
164 | 167 | in differents outputs like stdout, stderr, pyout |
|
165 | 168 | and status |
|
166 | 169 | |
|
167 | 170 | Arguments: |
|
168 | 171 | sub_msg: message receive from kernel in the sub socket channel |
|
169 | 172 | capture by kernel manager. |
|
170 | 173 | |
|
171 | 174 | """ |
|
172 | 175 | while self.km.sub_channel.was_called(): |
|
173 | 176 | sub_msg = self.km.sub_channel.get_msg() |
|
174 | 177 | if self.msg_header["username"] == sub_msg['parent_header']['username'] and self.km.session.session == sub_msg['parent_header']['session']: |
|
175 | 178 | if sub_msg['msg_type'] == 'status' : |
|
176 | 179 | if sub_msg["content"]["execution_state"] == "busy" : |
|
177 | 180 | pass |
|
178 | 181 | |
|
179 | 182 | if sub_msg['msg_type'] == 'stream' : |
|
180 | 183 | if sub_msg["content"]["name"] == "stdout": |
|
181 | 184 | print >> sys.stdout,sub_msg["content"]["data"] |
|
182 | 185 | sys.stdout.flush() |
|
183 | 186 | if sub_msg["content"]["name"] == "stderr" : |
|
184 | 187 | print >> sys.stderr,sub_msg["content"]["data"] |
|
185 | 188 | sys.stderr.flush() |
|
186 | 189 | |
|
187 | 190 | if sub_msg['msg_type'] == 'pyout' : |
|
188 | 191 | print >> sys.stdout,"Out[%i]:"%sub_msg["content"]["execution_count"], sub_msg["content"]["data"] |
|
189 | #print >> sys.stdout,"Out[%i]:"%self.msg_xreq["content"]["execution_count"], sub_msg["content"]["data"] | |
|
190 | 192 | sys.stdout.flush() |
|
191 | 193 | |
|
194 | def handle_rep_channel(self): | |
|
195 | """ Method to capture raw_input | |
|
196 | """ | |
|
197 | if self.km.rep_channel.was_called() : | |
|
198 | self.msg_rep = self.km.rep_channel.get_msg() | |
|
199 | #print self.msg_rep | |
|
200 | if self.msg_header["session"] == self.msg_rep["parent_header"]["session"] : | |
|
201 | raw_data = raw_input(self.msg_rep["content"]["prompt"]) | |
|
202 | self.km.rep_channel.input(raw_data) | |
|
203 | ||
|
204 | ||
|
205 | ||
|
192 | 206 | |
|
193 | 207 | def start_frontend(): |
|
194 | 208 | """ Entry point for application. |
|
195 | 209 | |
|
196 | 210 | """ |
|
197 | 211 | # Parse command line arguments. |
|
198 | 212 | parser = ArgumentParser() |
|
199 | 213 | kgroup = parser.add_argument_group('kernel options') |
|
200 | 214 | kgroup.add_argument('-e', '--existing', action='store_true', |
|
201 | 215 | help='connect to an existing kernel') |
|
202 | 216 | kgroup.add_argument('--ip', type=str, default=LOCALHOST, |
|
203 | 217 | help=\ |
|
204 | 218 | "set the kernel\'s IP address [default localhost].\ |
|
205 | 219 | If the IP address is something other than localhost, then \ |
|
206 | 220 | Consoles on other machines will be able to connect\ |
|
207 | 221 | to the Kernel, so be careful!") |
|
208 | 222 | kgroup.add_argument('--xreq', type=int, metavar='PORT', default=0, |
|
209 | 223 | help='set the XREQ channel port [default random]') |
|
210 | 224 | kgroup.add_argument('--sub', type=int, metavar='PORT', default=0, |
|
211 | 225 | help='set the SUB channel port [default random]') |
|
212 | 226 | kgroup.add_argument('--rep', type=int, metavar='PORT', default=0, |
|
213 | 227 | help='set the REP channel port [default random]') |
|
214 | 228 | kgroup.add_argument('--hb', type=int, metavar='PORT', default=0, |
|
215 | 229 | help='set the heartbeat port [default random]') |
|
216 | 230 | |
|
217 | 231 | egroup = kgroup.add_mutually_exclusive_group() |
|
218 | 232 | egroup.add_argument('--pure', action='store_true', help = \ |
|
219 | 233 | 'use a pure Python kernel instead of an IPython kernel') |
|
220 | 234 | egroup.add_argument('--pylab', type=str, metavar='GUI', nargs='?', |
|
221 | 235 | const='auto', help = \ |
|
222 | 236 | "Pre-load matplotlib and numpy for interactive use. If GUI is not \ |
|
223 | 237 | given, the GUI backend is matplotlib's, otherwise use one of: \ |
|
224 | 238 | ['tk', 'gtk', 'qt', 'wx', 'inline'].") |
|
225 | 239 | egroup.add_argument('--colors', type=str, |
|
226 | 240 | help="Set the color scheme (LightBG,Linux,NoColor). This is guessed\ |
|
227 | 241 | based on the pygments style if not set.") |
|
228 | 242 | |
|
229 | 243 | args = parser.parse_args() |
|
230 | 244 | |
|
231 | 245 | # parse the colors arg down to current known labels |
|
232 | 246 | if args.colors: |
|
233 | 247 | colors=args.colors.lower() |
|
234 | 248 | if colors in ('lightbg', 'light'): |
|
235 | 249 | colors='lightbg' |
|
236 | 250 | elif colors in ('dark', 'linux'): |
|
237 | 251 | colors='linux' |
|
238 | 252 | else: |
|
239 | 253 | colors='nocolor' |
|
240 | 254 | else: |
|
241 | 255 | colors=None |
|
242 | 256 | |
|
243 | 257 | # Create a KernelManager and start a kernel. |
|
244 | 258 | kernel_manager = KernelManager(xreq_address=(args.ip, args.xreq), |
|
245 | 259 | sub_address=(args.ip, args.sub), |
|
246 | 260 | rep_address=(args.ip, args.rep), |
|
247 | 261 | hb_address=(args.ip, args.hb)) |
|
248 | 262 | if not args.existing: |
|
249 | 263 | # if not args.ip in LOCAL_IPS+ALL_ALIAS: |
|
250 | 264 | # raise ValueError("Must bind a local ip, such as: %s"%LOCAL_IPS) |
|
251 | 265 | |
|
252 | 266 | kwargs = dict(ip=args.ip) |
|
253 | 267 | if args.pure: |
|
254 | 268 | kwargs['ipython']=False |
|
255 | 269 | else: |
|
256 | 270 | kwargs['colors']=colors |
|
257 | 271 | if args.pylab: |
|
258 | 272 | kwargs['pylab']=args.pylab |
|
259 | 273 | kernel_manager.start_kernel(**kwargs) |
|
260 | 274 | |
|
261 | 275 | |
|
262 | 276 | kernel_manager.start_channels() |
|
263 | 277 | time.sleep(4) |
|
264 | 278 | |
|
265 | 279 | frontend=Frontend(kernel_manager) |
|
266 | 280 | return frontend |
|
267 | 281 | |
|
268 | 282 | if __name__ == "__main__" : |
|
269 | 283 | frontend=start_frontend() |
|
270 | 284 | frontend.start() No newline at end of file |
General Comments 0
You need to be logged in to leave comments.
Login now