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