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