##// END OF EJS Templates
_encode_png needs to be in namespace of zmqshell.py
Thomas Kluyver -
Show More
@@ -1,446 +1,446 b''
1 """A ZMQ-based subclass of InteractiveShell.
1 """A ZMQ-based subclass of InteractiveShell.
2
2
3 This code is meant to ease the refactoring of the base InteractiveShell into
3 This code is meant to ease the refactoring of the base InteractiveShell into
4 something with a cleaner architecture for 2-process use, without actually
4 something with a cleaner architecture for 2-process use, without actually
5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
6 we subclass and override what we want to fix. Once this is working well, we
6 we subclass and override what we want to fix. Once this is working well, we
7 can go back to the base class and refactor the code for a cleaner inheritance
7 can go back to the base class and refactor the code for a cleaner inheritance
8 implementation that doesn't rely on so much monkeypatching.
8 implementation that doesn't rely on so much monkeypatching.
9
9
10 But this lets us maintain a fully working IPython as we develop the new
10 But this lets us maintain a fully working IPython as we develop the new
11 machinery. This should thus be thought of as scaffolding.
11 machinery. This should thus be thought of as scaffolding.
12 """
12 """
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16 from __future__ import print_function
17
17
18 # Stdlib
18 # Stdlib
19 import inspect
19 import inspect
20 import os
20 import os
21
21
22 # Our own
22 # Our own
23 from IPython.core.interactiveshell import (
23 from IPython.core.interactiveshell import (
24 InteractiveShell, InteractiveShellABC
24 InteractiveShell, InteractiveShellABC
25 )
25 )
26 from IPython.core import page
26 from IPython.core import page
27 from IPython.core.autocall import ZMQExitAutocall
27 from IPython.core.autocall import ZMQExitAutocall
28 from IPython.core.displaypub import DisplayPublisher
28 from IPython.core.displaypub import DisplayPublisher
29 from IPython.core.macro import Macro
29 from IPython.core.macro import Macro
30 from IPython.core.magic import MacroToEdit
30 from IPython.core.magic import MacroToEdit
31 from IPython.core.payloadpage import install_payload_page
31 from IPython.core.payloadpage import install_payload_page
32 from IPython.utils import io
32 from IPython.utils import io
33 from IPython.utils.path import get_py_filename
33 from IPython.utils.path import get_py_filename
34 from IPython.utils.traitlets import Instance, Type, Dict
34 from IPython.utils.traitlets import Instance, Type, Dict
35 from IPython.utils.warn import warn
35 from IPython.utils.warn import warn
36 from IPython.zmq.displayhook import ZMQShellDisplayHook
36 from IPython.zmq.displayhook import ZMQShellDisplayHook, _encode_png
37 from IPython.zmq.session import extract_header
37 from IPython.zmq.session import extract_header
38 from session import Session
38 from session import Session
39
39
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41 # Globals and side-effects
41 # Globals and side-effects
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43
43
44 # Install the payload version of page.
44 # Install the payload version of page.
45 install_payload_page()
45 install_payload_page()
46
46
47 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
48 # Functions and classes
48 # Functions and classes
49 #-----------------------------------------------------------------------------
49 #-----------------------------------------------------------------------------
50
50
51 class ZMQDisplayPublisher(DisplayPublisher):
51 class ZMQDisplayPublisher(DisplayPublisher):
52 """A display publisher that publishes data using a ZeroMQ PUB socket."""
52 """A display publisher that publishes data using a ZeroMQ PUB socket."""
53
53
54 session = Instance(Session)
54 session = Instance(Session)
55 pub_socket = Instance('zmq.Socket')
55 pub_socket = Instance('zmq.Socket')
56 parent_header = Dict({})
56 parent_header = Dict({})
57
57
58 def set_parent(self, parent):
58 def set_parent(self, parent):
59 """Set the parent for outbound messages."""
59 """Set the parent for outbound messages."""
60 self.parent_header = extract_header(parent)
60 self.parent_header = extract_header(parent)
61
61
62 def publish(self, source, data, metadata=None):
62 def publish(self, source, data, metadata=None):
63 if metadata is None:
63 if metadata is None:
64 metadata = {}
64 metadata = {}
65 self._validate_data(source, data, metadata)
65 self._validate_data(source, data, metadata)
66 content = {}
66 content = {}
67 content['source'] = source
67 content['source'] = source
68 _encode_png(data)
68 _encode_png(data)
69 content['data'] = data
69 content['data'] = data
70 content['metadata'] = metadata
70 content['metadata'] = metadata
71 self.session.send(
71 self.session.send(
72 self.pub_socket, u'display_data', content,
72 self.pub_socket, u'display_data', content,
73 parent=self.parent_header
73 parent=self.parent_header
74 )
74 )
75
75
76
76
77 class ZMQInteractiveShell(InteractiveShell):
77 class ZMQInteractiveShell(InteractiveShell):
78 """A subclass of InteractiveShell for ZMQ."""
78 """A subclass of InteractiveShell for ZMQ."""
79
79
80 displayhook_class = Type(ZMQShellDisplayHook)
80 displayhook_class = Type(ZMQShellDisplayHook)
81 display_pub_class = Type(ZMQDisplayPublisher)
81 display_pub_class = Type(ZMQDisplayPublisher)
82
82
83 exiter = Instance(ZMQExitAutocall)
83 exiter = Instance(ZMQExitAutocall)
84 def _exiter_default(self):
84 def _exiter_default(self):
85 return ZMQExitAutocall(self)
85 return ZMQExitAutocall(self)
86
86
87 keepkernel_on_exit = None
87 keepkernel_on_exit = None
88
88
89 def init_environment(self):
89 def init_environment(self):
90 """Configure the user's environment.
90 """Configure the user's environment.
91
91
92 """
92 """
93 env = os.environ
93 env = os.environ
94 # These two ensure 'ls' produces nice coloring on BSD-derived systems
94 # These two ensure 'ls' produces nice coloring on BSD-derived systems
95 env['TERM'] = 'xterm-color'
95 env['TERM'] = 'xterm-color'
96 env['CLICOLOR'] = '1'
96 env['CLICOLOR'] = '1'
97 # Since normal pagers don't work at all (over pexpect we don't have
97 # Since normal pagers don't work at all (over pexpect we don't have
98 # single-key control of the subprocess), try to disable paging in
98 # single-key control of the subprocess), try to disable paging in
99 # subprocesses as much as possible.
99 # subprocesses as much as possible.
100 env['PAGER'] = 'cat'
100 env['PAGER'] = 'cat'
101 env['GIT_PAGER'] = 'cat'
101 env['GIT_PAGER'] = 'cat'
102
102
103 def auto_rewrite_input(self, cmd):
103 def auto_rewrite_input(self, cmd):
104 """Called to show the auto-rewritten input for autocall and friends.
104 """Called to show the auto-rewritten input for autocall and friends.
105
105
106 FIXME: this payload is currently not correctly processed by the
106 FIXME: this payload is currently not correctly processed by the
107 frontend.
107 frontend.
108 """
108 """
109 new = self.displayhook.prompt1.auto_rewrite() + cmd
109 new = self.displayhook.prompt1.auto_rewrite() + cmd
110 payload = dict(
110 payload = dict(
111 source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input',
111 source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input',
112 transformed_input=new,
112 transformed_input=new,
113 )
113 )
114 self.payload_manager.write_payload(payload)
114 self.payload_manager.write_payload(payload)
115
115
116 def ask_exit(self):
116 def ask_exit(self):
117 """Engage the exit actions."""
117 """Engage the exit actions."""
118 payload = dict(
118 payload = dict(
119 source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit',
119 source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit',
120 exit=True,
120 exit=True,
121 keepkernel=self.keepkernel_on_exit,
121 keepkernel=self.keepkernel_on_exit,
122 )
122 )
123 self.payload_manager.write_payload(payload)
123 self.payload_manager.write_payload(payload)
124
124
125 def _showtraceback(self, etype, evalue, stb):
125 def _showtraceback(self, etype, evalue, stb):
126
126
127 exc_content = {
127 exc_content = {
128 u'traceback' : stb,
128 u'traceback' : stb,
129 u'ename' : unicode(etype.__name__),
129 u'ename' : unicode(etype.__name__),
130 u'evalue' : unicode(evalue)
130 u'evalue' : unicode(evalue)
131 }
131 }
132
132
133 dh = self.displayhook
133 dh = self.displayhook
134 # Send exception info over pub socket for other clients than the caller
134 # Send exception info over pub socket for other clients than the caller
135 # to pick up
135 # to pick up
136 exc_msg = dh.session.send(dh.pub_socket, u'pyerr', exc_content, dh.parent_header)
136 exc_msg = dh.session.send(dh.pub_socket, u'pyerr', exc_content, dh.parent_header)
137
137
138 # FIXME - Hack: store exception info in shell object. Right now, the
138 # FIXME - Hack: store exception info in shell object. Right now, the
139 # caller is reading this info after the fact, we need to fix this logic
139 # caller is reading this info after the fact, we need to fix this logic
140 # to remove this hack. Even uglier, we need to store the error status
140 # to remove this hack. Even uglier, we need to store the error status
141 # here, because in the main loop, the logic that sets it is being
141 # here, because in the main loop, the logic that sets it is being
142 # skipped because runlines swallows the exceptions.
142 # skipped because runlines swallows the exceptions.
143 exc_content[u'status'] = u'error'
143 exc_content[u'status'] = u'error'
144 self._reply_content = exc_content
144 self._reply_content = exc_content
145 # /FIXME
145 # /FIXME
146
146
147 return exc_content
147 return exc_content
148
148
149 #------------------------------------------------------------------------
149 #------------------------------------------------------------------------
150 # Magic overrides
150 # Magic overrides
151 #------------------------------------------------------------------------
151 #------------------------------------------------------------------------
152 # Once the base class stops inheriting from magic, this code needs to be
152 # Once the base class stops inheriting from magic, this code needs to be
153 # moved into a separate machinery as well. For now, at least isolate here
153 # moved into a separate machinery as well. For now, at least isolate here
154 # the magics which this class needs to implement differently from the base
154 # the magics which this class needs to implement differently from the base
155 # class, or that are unique to it.
155 # class, or that are unique to it.
156
156
157 def magic_doctest_mode(self,parameter_s=''):
157 def magic_doctest_mode(self,parameter_s=''):
158 """Toggle doctest mode on and off.
158 """Toggle doctest mode on and off.
159
159
160 This mode is intended to make IPython behave as much as possible like a
160 This mode is intended to make IPython behave as much as possible like a
161 plain Python shell, from the perspective of how its prompts, exceptions
161 plain Python shell, from the perspective of how its prompts, exceptions
162 and output look. This makes it easy to copy and paste parts of a
162 and output look. This makes it easy to copy and paste parts of a
163 session into doctests. It does so by:
163 session into doctests. It does so by:
164
164
165 - Changing the prompts to the classic ``>>>`` ones.
165 - Changing the prompts to the classic ``>>>`` ones.
166 - Changing the exception reporting mode to 'Plain'.
166 - Changing the exception reporting mode to 'Plain'.
167 - Disabling pretty-printing of output.
167 - Disabling pretty-printing of output.
168
168
169 Note that IPython also supports the pasting of code snippets that have
169 Note that IPython also supports the pasting of code snippets that have
170 leading '>>>' and '...' prompts in them. This means that you can paste
170 leading '>>>' and '...' prompts in them. This means that you can paste
171 doctests from files or docstrings (even if they have leading
171 doctests from files or docstrings (even if they have leading
172 whitespace), and the code will execute correctly. You can then use
172 whitespace), and the code will execute correctly. You can then use
173 '%history -t' to see the translated history; this will give you the
173 '%history -t' to see the translated history; this will give you the
174 input after removal of all the leading prompts and whitespace, which
174 input after removal of all the leading prompts and whitespace, which
175 can be pasted back into an editor.
175 can be pasted back into an editor.
176
176
177 With these features, you can switch into this mode easily whenever you
177 With these features, you can switch into this mode easily whenever you
178 need to do testing and changes to doctests, without having to leave
178 need to do testing and changes to doctests, without having to leave
179 your existing IPython session.
179 your existing IPython session.
180 """
180 """
181
181
182 from IPython.utils.ipstruct import Struct
182 from IPython.utils.ipstruct import Struct
183
183
184 # Shorthands
184 # Shorthands
185 shell = self.shell
185 shell = self.shell
186 disp_formatter = self.shell.display_formatter
186 disp_formatter = self.shell.display_formatter
187 ptformatter = disp_formatter.formatters['text/plain']
187 ptformatter = disp_formatter.formatters['text/plain']
188 # dstore is a data store kept in the instance metadata bag to track any
188 # dstore is a data store kept in the instance metadata bag to track any
189 # changes we make, so we can undo them later.
189 # changes we make, so we can undo them later.
190 dstore = shell.meta.setdefault('doctest_mode', Struct())
190 dstore = shell.meta.setdefault('doctest_mode', Struct())
191 save_dstore = dstore.setdefault
191 save_dstore = dstore.setdefault
192
192
193 # save a few values we'll need to recover later
193 # save a few values we'll need to recover later
194 mode = save_dstore('mode', False)
194 mode = save_dstore('mode', False)
195 save_dstore('rc_pprint', ptformatter.pprint)
195 save_dstore('rc_pprint', ptformatter.pprint)
196 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
196 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
197 save_dstore('xmode', shell.InteractiveTB.mode)
197 save_dstore('xmode', shell.InteractiveTB.mode)
198
198
199 if mode == False:
199 if mode == False:
200 # turn on
200 # turn on
201 ptformatter.pprint = False
201 ptformatter.pprint = False
202 disp_formatter.plain_text_only = True
202 disp_formatter.plain_text_only = True
203 shell.magic_xmode('Plain')
203 shell.magic_xmode('Plain')
204 else:
204 else:
205 # turn off
205 # turn off
206 ptformatter.pprint = dstore.rc_pprint
206 ptformatter.pprint = dstore.rc_pprint
207 disp_formatter.plain_text_only = dstore.rc_plain_text_only
207 disp_formatter.plain_text_only = dstore.rc_plain_text_only
208 shell.magic_xmode(dstore.xmode)
208 shell.magic_xmode(dstore.xmode)
209
209
210 # Store new mode and inform on console
210 # Store new mode and inform on console
211 dstore.mode = bool(1-int(mode))
211 dstore.mode = bool(1-int(mode))
212 mode_label = ['OFF','ON'][dstore.mode]
212 mode_label = ['OFF','ON'][dstore.mode]
213 print('Doctest mode is:', mode_label)
213 print('Doctest mode is:', mode_label)
214
214
215 # Send the payload back so that clients can modify their prompt display
215 # Send the payload back so that clients can modify their prompt display
216 payload = dict(
216 payload = dict(
217 source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode',
217 source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode',
218 mode=dstore.mode)
218 mode=dstore.mode)
219 self.payload_manager.write_payload(payload)
219 self.payload_manager.write_payload(payload)
220
220
221 def magic_edit(self,parameter_s='',last_call=['','']):
221 def magic_edit(self,parameter_s='',last_call=['','']):
222 """Bring up an editor and execute the resulting code.
222 """Bring up an editor and execute the resulting code.
223
223
224 Usage:
224 Usage:
225 %edit [options] [args]
225 %edit [options] [args]
226
226
227 %edit runs IPython's editor hook. The default version of this hook is
227 %edit runs IPython's editor hook. The default version of this hook is
228 set to call the __IPYTHON__.rc.editor command. This is read from your
228 set to call the __IPYTHON__.rc.editor command. This is read from your
229 environment variable $EDITOR. If this isn't found, it will default to
229 environment variable $EDITOR. If this isn't found, it will default to
230 vi under Linux/Unix and to notepad under Windows. See the end of this
230 vi under Linux/Unix and to notepad under Windows. See the end of this
231 docstring for how to change the editor hook.
231 docstring for how to change the editor hook.
232
232
233 You can also set the value of this editor via the command line option
233 You can also set the value of this editor via the command line option
234 '-editor' or in your ipythonrc file. This is useful if you wish to use
234 '-editor' or in your ipythonrc file. This is useful if you wish to use
235 specifically for IPython an editor different from your typical default
235 specifically for IPython an editor different from your typical default
236 (and for Windows users who typically don't set environment variables).
236 (and for Windows users who typically don't set environment variables).
237
237
238 This command allows you to conveniently edit multi-line code right in
238 This command allows you to conveniently edit multi-line code right in
239 your IPython session.
239 your IPython session.
240
240
241 If called without arguments, %edit opens up an empty editor with a
241 If called without arguments, %edit opens up an empty editor with a
242 temporary file and will execute the contents of this file when you
242 temporary file and will execute the contents of this file when you
243 close it (don't forget to save it!).
243 close it (don't forget to save it!).
244
244
245
245
246 Options:
246 Options:
247
247
248 -n <number>: open the editor at a specified line number. By default,
248 -n <number>: open the editor at a specified line number. By default,
249 the IPython editor hook uses the unix syntax 'editor +N filename', but
249 the IPython editor hook uses the unix syntax 'editor +N filename', but
250 you can configure this by providing your own modified hook if your
250 you can configure this by providing your own modified hook if your
251 favorite editor supports line-number specifications with a different
251 favorite editor supports line-number specifications with a different
252 syntax.
252 syntax.
253
253
254 -p: this will call the editor with the same data as the previous time
254 -p: this will call the editor with the same data as the previous time
255 it was used, regardless of how long ago (in your current session) it
255 it was used, regardless of how long ago (in your current session) it
256 was.
256 was.
257
257
258 -r: use 'raw' input. This option only applies to input taken from the
258 -r: use 'raw' input. This option only applies to input taken from the
259 user's history. By default, the 'processed' history is used, so that
259 user's history. By default, the 'processed' history is used, so that
260 magics are loaded in their transformed version to valid Python. If
260 magics are loaded in their transformed version to valid Python. If
261 this option is given, the raw input as typed as the command line is
261 this option is given, the raw input as typed as the command line is
262 used instead. When you exit the editor, it will be executed by
262 used instead. When you exit the editor, it will be executed by
263 IPython's own processor.
263 IPython's own processor.
264
264
265 -x: do not execute the edited code immediately upon exit. This is
265 -x: do not execute the edited code immediately upon exit. This is
266 mainly useful if you are editing programs which need to be called with
266 mainly useful if you are editing programs which need to be called with
267 command line arguments, which you can then do using %run.
267 command line arguments, which you can then do using %run.
268
268
269
269
270 Arguments:
270 Arguments:
271
271
272 If arguments are given, the following possibilites exist:
272 If arguments are given, the following possibilites exist:
273
273
274 - The arguments are numbers or pairs of colon-separated numbers (like
274 - The arguments are numbers or pairs of colon-separated numbers (like
275 1 4:8 9). These are interpreted as lines of previous input to be
275 1 4:8 9). These are interpreted as lines of previous input to be
276 loaded into the editor. The syntax is the same of the %macro command.
276 loaded into the editor. The syntax is the same of the %macro command.
277
277
278 - If the argument doesn't start with a number, it is evaluated as a
278 - If the argument doesn't start with a number, it is evaluated as a
279 variable and its contents loaded into the editor. You can thus edit
279 variable and its contents loaded into the editor. You can thus edit
280 any string which contains python code (including the result of
280 any string which contains python code (including the result of
281 previous edits).
281 previous edits).
282
282
283 - If the argument is the name of an object (other than a string),
283 - If the argument is the name of an object (other than a string),
284 IPython will try to locate the file where it was defined and open the
284 IPython will try to locate the file where it was defined and open the
285 editor at the point where it is defined. You can use `%edit function`
285 editor at the point where it is defined. You can use `%edit function`
286 to load an editor exactly at the point where 'function' is defined,
286 to load an editor exactly at the point where 'function' is defined,
287 edit it and have the file be executed automatically.
287 edit it and have the file be executed automatically.
288
288
289 If the object is a macro (see %macro for details), this opens up your
289 If the object is a macro (see %macro for details), this opens up your
290 specified editor with a temporary file containing the macro's data.
290 specified editor with a temporary file containing the macro's data.
291 Upon exit, the macro is reloaded with the contents of the file.
291 Upon exit, the macro is reloaded with the contents of the file.
292
292
293 Note: opening at an exact line is only supported under Unix, and some
293 Note: opening at an exact line is only supported under Unix, and some
294 editors (like kedit and gedit up to Gnome 2.8) do not understand the
294 editors (like kedit and gedit up to Gnome 2.8) do not understand the
295 '+NUMBER' parameter necessary for this feature. Good editors like
295 '+NUMBER' parameter necessary for this feature. Good editors like
296 (X)Emacs, vi, jed, pico and joe all do.
296 (X)Emacs, vi, jed, pico and joe all do.
297
297
298 - If the argument is not found as a variable, IPython will look for a
298 - If the argument is not found as a variable, IPython will look for a
299 file with that name (adding .py if necessary) and load it into the
299 file with that name (adding .py if necessary) and load it into the
300 editor. It will execute its contents with execfile() when you exit,
300 editor. It will execute its contents with execfile() when you exit,
301 loading any code in the file into your interactive namespace.
301 loading any code in the file into your interactive namespace.
302
302
303 After executing your code, %edit will return as output the code you
303 After executing your code, %edit will return as output the code you
304 typed in the editor (except when it was an existing file). This way
304 typed in the editor (except when it was an existing file). This way
305 you can reload the code in further invocations of %edit as a variable,
305 you can reload the code in further invocations of %edit as a variable,
306 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
306 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
307 the output.
307 the output.
308
308
309 Note that %edit is also available through the alias %ed.
309 Note that %edit is also available through the alias %ed.
310
310
311 This is an example of creating a simple function inside the editor and
311 This is an example of creating a simple function inside the editor and
312 then modifying it. First, start up the editor:
312 then modifying it. First, start up the editor:
313
313
314 In [1]: ed
314 In [1]: ed
315 Editing... done. Executing edited code...
315 Editing... done. Executing edited code...
316 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
316 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
317
317
318 We can then call the function foo():
318 We can then call the function foo():
319
319
320 In [2]: foo()
320 In [2]: foo()
321 foo() was defined in an editing session
321 foo() was defined in an editing session
322
322
323 Now we edit foo. IPython automatically loads the editor with the
323 Now we edit foo. IPython automatically loads the editor with the
324 (temporary) file where foo() was previously defined:
324 (temporary) file where foo() was previously defined:
325
325
326 In [3]: ed foo
326 In [3]: ed foo
327 Editing... done. Executing edited code...
327 Editing... done. Executing edited code...
328
328
329 And if we call foo() again we get the modified version:
329 And if we call foo() again we get the modified version:
330
330
331 In [4]: foo()
331 In [4]: foo()
332 foo() has now been changed!
332 foo() has now been changed!
333
333
334 Here is an example of how to edit a code snippet successive
334 Here is an example of how to edit a code snippet successive
335 times. First we call the editor:
335 times. First we call the editor:
336
336
337 In [5]: ed
337 In [5]: ed
338 Editing... done. Executing edited code...
338 Editing... done. Executing edited code...
339 hello
339 hello
340 Out[5]: "print 'hello'n"
340 Out[5]: "print 'hello'n"
341
341
342 Now we call it again with the previous output (stored in _):
342 Now we call it again with the previous output (stored in _):
343
343
344 In [6]: ed _
344 In [6]: ed _
345 Editing... done. Executing edited code...
345 Editing... done. Executing edited code...
346 hello world
346 hello world
347 Out[6]: "print 'hello world'n"
347 Out[6]: "print 'hello world'n"
348
348
349 Now we call it with the output #8 (stored in _8, also as Out[8]):
349 Now we call it with the output #8 (stored in _8, also as Out[8]):
350
350
351 In [7]: ed _8
351 In [7]: ed _8
352 Editing... done. Executing edited code...
352 Editing... done. Executing edited code...
353 hello again
353 hello again
354 Out[7]: "print 'hello again'n"
354 Out[7]: "print 'hello again'n"
355
355
356
356
357 Changing the default editor hook:
357 Changing the default editor hook:
358
358
359 If you wish to write your own editor hook, you can put it in a
359 If you wish to write your own editor hook, you can put it in a
360 configuration file which you load at startup time. The default hook
360 configuration file which you load at startup time. The default hook
361 is defined in the IPython.core.hooks module, and you can use that as a
361 is defined in the IPython.core.hooks module, and you can use that as a
362 starting example for further modifications. That file also has
362 starting example for further modifications. That file also has
363 general instructions on how to set a new hook for use once you've
363 general instructions on how to set a new hook for use once you've
364 defined it."""
364 defined it."""
365
365
366 opts,args = self.parse_options(parameter_s,'prn:')
366 opts,args = self.parse_options(parameter_s,'prn:')
367
367
368 try:
368 try:
369 filename, lineno, _ = self._find_edit_target(args, opts, last_call)
369 filename, lineno, _ = self._find_edit_target(args, opts, last_call)
370 except MacroToEdit as e:
370 except MacroToEdit as e:
371 # TODO: Implement macro editing over 2 processes.
371 # TODO: Implement macro editing over 2 processes.
372 print("Macro editing not yet implemented in 2-process model.")
372 print("Macro editing not yet implemented in 2-process model.")
373 return
373 return
374
374
375 # Make sure we send to the client an absolute path, in case the working
375 # Make sure we send to the client an absolute path, in case the working
376 # directory of client and kernel don't match
376 # directory of client and kernel don't match
377 filename = os.path.abspath(filename)
377 filename = os.path.abspath(filename)
378
378
379 payload = {
379 payload = {
380 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
380 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
381 'filename' : filename,
381 'filename' : filename,
382 'line_number' : lineno
382 'line_number' : lineno
383 }
383 }
384 self.payload_manager.write_payload(payload)
384 self.payload_manager.write_payload(payload)
385
385
386 def magic_gui(self, *args, **kwargs):
386 def magic_gui(self, *args, **kwargs):
387 raise NotImplementedError(
387 raise NotImplementedError(
388 'GUI support must be enabled in command line options.')
388 'GUI support must be enabled in command line options.')
389
389
390 def magic_pylab(self, *args, **kwargs):
390 def magic_pylab(self, *args, **kwargs):
391 raise NotImplementedError(
391 raise NotImplementedError(
392 'pylab support must be enabled in command line options.')
392 'pylab support must be enabled in command line options.')
393
393
394 # A few magics that are adapted to the specifics of using pexpect and a
394 # A few magics that are adapted to the specifics of using pexpect and a
395 # remote terminal
395 # remote terminal
396
396
397 def magic_clear(self, arg_s):
397 def magic_clear(self, arg_s):
398 """Clear the terminal."""
398 """Clear the terminal."""
399 if os.name == 'posix':
399 if os.name == 'posix':
400 self.shell.system("clear")
400 self.shell.system("clear")
401 else:
401 else:
402 self.shell.system("cls")
402 self.shell.system("cls")
403
403
404 if os.name == 'nt':
404 if os.name == 'nt':
405 # This is the usual name in windows
405 # This is the usual name in windows
406 magic_cls = magic_clear
406 magic_cls = magic_clear
407
407
408 # Terminal pagers won't work over pexpect, but we do have our own pager
408 # Terminal pagers won't work over pexpect, but we do have our own pager
409
409
410 def magic_less(self, arg_s):
410 def magic_less(self, arg_s):
411 """Show a file through the pager.
411 """Show a file through the pager.
412
412
413 Files ending in .py are syntax-highlighted."""
413 Files ending in .py are syntax-highlighted."""
414 cont = open(arg_s).read()
414 cont = open(arg_s).read()
415 if arg_s.endswith('.py'):
415 if arg_s.endswith('.py'):
416 cont = self.shell.pycolorize(cont)
416 cont = self.shell.pycolorize(cont)
417 page.page(cont)
417 page.page(cont)
418
418
419 magic_more = magic_less
419 magic_more = magic_less
420
420
421 # Man calls a pager, so we also need to redefine it
421 # Man calls a pager, so we also need to redefine it
422 if os.name == 'posix':
422 if os.name == 'posix':
423 def magic_man(self, arg_s):
423 def magic_man(self, arg_s):
424 """Find the man page for the given command and display in pager."""
424 """Find the man page for the given command and display in pager."""
425 page.page(self.shell.getoutput('man %s | col -b' % arg_s,
425 page.page(self.shell.getoutput('man %s | col -b' % arg_s,
426 split=False))
426 split=False))
427
427
428 # FIXME: this is specific to the GUI, so we should let the gui app load
428 # FIXME: this is specific to the GUI, so we should let the gui app load
429 # magics at startup that are only for the gui. Once the gui app has proper
429 # magics at startup that are only for the gui. Once the gui app has proper
430 # profile and configuration management, we can have it initialize a kernel
430 # profile and configuration management, we can have it initialize a kernel
431 # with a special config file that provides these.
431 # with a special config file that provides these.
432 def magic_guiref(self, arg_s):
432 def magic_guiref(self, arg_s):
433 """Show a basic reference about the GUI console."""
433 """Show a basic reference about the GUI console."""
434 from IPython.core.usage import gui_reference
434 from IPython.core.usage import gui_reference
435 page.page(gui_reference, auto_html=True)
435 page.page(gui_reference, auto_html=True)
436
436
437 def set_next_input(self, text):
437 def set_next_input(self, text):
438 """Send the specified text to the frontend to be presented at the next
438 """Send the specified text to the frontend to be presented at the next
439 input cell."""
439 input cell."""
440 payload = dict(
440 payload = dict(
441 source='IPython.zmq.zmqshell.ZMQInteractiveShell.set_next_input',
441 source='IPython.zmq.zmqshell.ZMQInteractiveShell.set_next_input',
442 text=text
442 text=text
443 )
443 )
444 self.payload_manager.write_payload(payload)
444 self.payload_manager.write_payload(payload)
445
445
446 InteractiveShellABC.register(ZMQInteractiveShell)
446 InteractiveShellABC.register(ZMQInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now