##// END OF EJS Templates
propagate deprecation of Formatter.plain_text_only
MinRK -
Show More
@@ -1,613 +1,613 b''
1 """Implementation of basic magic functions.
1 """Implementation of basic magic functions.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
4 # Copyright (c) 2012 The IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 from __future__ import print_function
14 from __future__ import print_function
15
15
16 # Stdlib
16 # Stdlib
17 import io
17 import io
18 import sys
18 import sys
19 from pprint import pformat
19 from pprint import pformat
20
20
21 # Our own packages
21 # Our own packages
22 from IPython.core import magic_arguments
22 from IPython.core import magic_arguments
23 from IPython.core.error import UsageError
23 from IPython.core.error import UsageError
24 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
24 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
25 from IPython.utils.text import format_screen, dedent, indent
25 from IPython.utils.text import format_screen, dedent, indent
26 from IPython.core import magic_arguments, page
26 from IPython.core import magic_arguments, page
27 from IPython.testing.skipdoctest import skip_doctest
27 from IPython.testing.skipdoctest import skip_doctest
28 from IPython.utils.ipstruct import Struct
28 from IPython.utils.ipstruct import Struct
29 from IPython.utils.path import unquote_filename
29 from IPython.utils.path import unquote_filename
30 from IPython.utils.warn import warn, error
30 from IPython.utils.warn import warn, error
31
31
32 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
33 # Magics class implementation
33 # Magics class implementation
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35
35
36 @magics_class
36 @magics_class
37 class BasicMagics(Magics):
37 class BasicMagics(Magics):
38 """Magics that provide central IPython functionality.
38 """Magics that provide central IPython functionality.
39
39
40 These are various magics that don't fit into specific categories but that
40 These are various magics that don't fit into specific categories but that
41 are all part of the base 'IPython experience'."""
41 are all part of the base 'IPython experience'."""
42
42
43 @magic_arguments.magic_arguments()
43 @magic_arguments.magic_arguments()
44 @magic_arguments.argument(
44 @magic_arguments.argument(
45 '-l', '--line', action='store_true',
45 '-l', '--line', action='store_true',
46 help="""Create a line magic alias."""
46 help="""Create a line magic alias."""
47 )
47 )
48 @magic_arguments.argument(
48 @magic_arguments.argument(
49 '-c', '--cell', action='store_true',
49 '-c', '--cell', action='store_true',
50 help="""Create a cell magic alias."""
50 help="""Create a cell magic alias."""
51 )
51 )
52 @magic_arguments.argument(
52 @magic_arguments.argument(
53 'name',
53 'name',
54 help="""Name of the magic to be created."""
54 help="""Name of the magic to be created."""
55 )
55 )
56 @magic_arguments.argument(
56 @magic_arguments.argument(
57 'target',
57 'target',
58 help="""Name of the existing line or cell magic."""
58 help="""Name of the existing line or cell magic."""
59 )
59 )
60 @line_magic
60 @line_magic
61 def alias_magic(self, line=''):
61 def alias_magic(self, line=''):
62 """Create an alias for an existing line or cell magic.
62 """Create an alias for an existing line or cell magic.
63
63
64 Examples
64 Examples
65 --------
65 --------
66 ::
66 ::
67 In [1]: %alias_magic t timeit
67 In [1]: %alias_magic t timeit
68 Created `%t` as an alias for `%timeit`.
68 Created `%t` as an alias for `%timeit`.
69 Created `%%t` as an alias for `%%timeit`.
69 Created `%%t` as an alias for `%%timeit`.
70
70
71 In [2]: %t -n1 pass
71 In [2]: %t -n1 pass
72 1 loops, best of 3: 954 ns per loop
72 1 loops, best of 3: 954 ns per loop
73
73
74 In [3]: %%t -n1
74 In [3]: %%t -n1
75 ...: pass
75 ...: pass
76 ...:
76 ...:
77 1 loops, best of 3: 954 ns per loop
77 1 loops, best of 3: 954 ns per loop
78
78
79 In [4]: %alias_magic --cell whereami pwd
79 In [4]: %alias_magic --cell whereami pwd
80 UsageError: Cell magic function `%%pwd` not found.
80 UsageError: Cell magic function `%%pwd` not found.
81 In [5]: %alias_magic --line whereami pwd
81 In [5]: %alias_magic --line whereami pwd
82 Created `%whereami` as an alias for `%pwd`.
82 Created `%whereami` as an alias for `%pwd`.
83
83
84 In [6]: %whereami
84 In [6]: %whereami
85 Out[6]: u'/home/testuser'
85 Out[6]: u'/home/testuser'
86 """
86 """
87 args = magic_arguments.parse_argstring(self.alias_magic, line)
87 args = magic_arguments.parse_argstring(self.alias_magic, line)
88 shell = self.shell
88 shell = self.shell
89 mman = self.shell.magics_manager
89 mman = self.shell.magics_manager
90 escs = ''.join(magic_escapes.values())
90 escs = ''.join(magic_escapes.values())
91
91
92 target = args.target.lstrip(escs)
92 target = args.target.lstrip(escs)
93 name = args.name.lstrip(escs)
93 name = args.name.lstrip(escs)
94
94
95 # Find the requested magics.
95 # Find the requested magics.
96 m_line = shell.find_magic(target, 'line')
96 m_line = shell.find_magic(target, 'line')
97 m_cell = shell.find_magic(target, 'cell')
97 m_cell = shell.find_magic(target, 'cell')
98 if args.line and m_line is None:
98 if args.line and m_line is None:
99 raise UsageError('Line magic function `%s%s` not found.' %
99 raise UsageError('Line magic function `%s%s` not found.' %
100 (magic_escapes['line'], target))
100 (magic_escapes['line'], target))
101 if args.cell and m_cell is None:
101 if args.cell and m_cell is None:
102 raise UsageError('Cell magic function `%s%s` not found.' %
102 raise UsageError('Cell magic function `%s%s` not found.' %
103 (magic_escapes['cell'], target))
103 (magic_escapes['cell'], target))
104
104
105 # If --line and --cell are not specified, default to the ones
105 # If --line and --cell are not specified, default to the ones
106 # that are available.
106 # that are available.
107 if not args.line and not args.cell:
107 if not args.line and not args.cell:
108 if not m_line and not m_cell:
108 if not m_line and not m_cell:
109 raise UsageError(
109 raise UsageError(
110 'No line or cell magic with name `%s` found.' % target
110 'No line or cell magic with name `%s` found.' % target
111 )
111 )
112 args.line = bool(m_line)
112 args.line = bool(m_line)
113 args.cell = bool(m_cell)
113 args.cell = bool(m_cell)
114
114
115 if args.line:
115 if args.line:
116 mman.register_alias(name, target, 'line')
116 mman.register_alias(name, target, 'line')
117 print('Created `%s%s` as an alias for `%s%s`.' % (
117 print('Created `%s%s` as an alias for `%s%s`.' % (
118 magic_escapes['line'], name,
118 magic_escapes['line'], name,
119 magic_escapes['line'], target))
119 magic_escapes['line'], target))
120
120
121 if args.cell:
121 if args.cell:
122 mman.register_alias(name, target, 'cell')
122 mman.register_alias(name, target, 'cell')
123 print('Created `%s%s` as an alias for `%s%s`.' % (
123 print('Created `%s%s` as an alias for `%s%s`.' % (
124 magic_escapes['cell'], name,
124 magic_escapes['cell'], name,
125 magic_escapes['cell'], target))
125 magic_escapes['cell'], target))
126
126
127 def _lsmagic(self):
127 def _lsmagic(self):
128 mesc = magic_escapes['line']
128 mesc = magic_escapes['line']
129 cesc = magic_escapes['cell']
129 cesc = magic_escapes['cell']
130 mman = self.shell.magics_manager
130 mman = self.shell.magics_manager
131 magics = mman.lsmagic()
131 magics = mman.lsmagic()
132 out = ['Available line magics:',
132 out = ['Available line magics:',
133 mesc + (' '+mesc).join(sorted(magics['line'])),
133 mesc + (' '+mesc).join(sorted(magics['line'])),
134 '',
134 '',
135 'Available cell magics:',
135 'Available cell magics:',
136 cesc + (' '+cesc).join(sorted(magics['cell'])),
136 cesc + (' '+cesc).join(sorted(magics['cell'])),
137 '',
137 '',
138 mman.auto_status()]
138 mman.auto_status()]
139 return '\n'.join(out)
139 return '\n'.join(out)
140
140
141 @line_magic
141 @line_magic
142 def lsmagic(self, parameter_s=''):
142 def lsmagic(self, parameter_s=''):
143 """List currently available magic functions."""
143 """List currently available magic functions."""
144 print(self._lsmagic())
144 print(self._lsmagic())
145
145
146 def _magic_docs(self, brief=False, rest=False):
146 def _magic_docs(self, brief=False, rest=False):
147 """Return docstrings from magic functions."""
147 """Return docstrings from magic functions."""
148 mman = self.shell.magics_manager
148 mman = self.shell.magics_manager
149 docs = mman.lsmagic_docs(brief, missing='No documentation')
149 docs = mman.lsmagic_docs(brief, missing='No documentation')
150
150
151 if rest:
151 if rest:
152 format_string = '**%s%s**::\n\n%s\n\n'
152 format_string = '**%s%s**::\n\n%s\n\n'
153 else:
153 else:
154 format_string = '%s%s:\n%s\n'
154 format_string = '%s%s:\n%s\n'
155
155
156 return ''.join(
156 return ''.join(
157 [format_string % (magic_escapes['line'], fname,
157 [format_string % (magic_escapes['line'], fname,
158 indent(dedent(fndoc)))
158 indent(dedent(fndoc)))
159 for fname, fndoc in sorted(docs['line'].items())]
159 for fname, fndoc in sorted(docs['line'].items())]
160 +
160 +
161 [format_string % (magic_escapes['cell'], fname,
161 [format_string % (magic_escapes['cell'], fname,
162 indent(dedent(fndoc)))
162 indent(dedent(fndoc)))
163 for fname, fndoc in sorted(docs['cell'].items())]
163 for fname, fndoc in sorted(docs['cell'].items())]
164 )
164 )
165
165
166 @line_magic
166 @line_magic
167 def magic(self, parameter_s=''):
167 def magic(self, parameter_s=''):
168 """Print information about the magic function system.
168 """Print information about the magic function system.
169
169
170 Supported formats: -latex, -brief, -rest
170 Supported formats: -latex, -brief, -rest
171 """
171 """
172
172
173 mode = ''
173 mode = ''
174 try:
174 try:
175 mode = parameter_s.split()[0][1:]
175 mode = parameter_s.split()[0][1:]
176 if mode == 'rest':
176 if mode == 'rest':
177 rest_docs = []
177 rest_docs = []
178 except IndexError:
178 except IndexError:
179 pass
179 pass
180
180
181 brief = (mode == 'brief')
181 brief = (mode == 'brief')
182 rest = (mode == 'rest')
182 rest = (mode == 'rest')
183 magic_docs = self._magic_docs(brief, rest)
183 magic_docs = self._magic_docs(brief, rest)
184
184
185 if mode == 'latex':
185 if mode == 'latex':
186 print(self.format_latex(magic_docs))
186 print(self.format_latex(magic_docs))
187 return
187 return
188 else:
188 else:
189 magic_docs = format_screen(magic_docs)
189 magic_docs = format_screen(magic_docs)
190
190
191 out = ["""
191 out = ["""
192 IPython's 'magic' functions
192 IPython's 'magic' functions
193 ===========================
193 ===========================
194
194
195 The magic function system provides a series of functions which allow you to
195 The magic function system provides a series of functions which allow you to
196 control the behavior of IPython itself, plus a lot of system-type
196 control the behavior of IPython itself, plus a lot of system-type
197 features. There are two kinds of magics, line-oriented and cell-oriented.
197 features. There are two kinds of magics, line-oriented and cell-oriented.
198
198
199 Line magics are prefixed with the % character and work much like OS
199 Line magics are prefixed with the % character and work much like OS
200 command-line calls: they get as an argument the rest of the line, where
200 command-line calls: they get as an argument the rest of the line, where
201 arguments are passed without parentheses or quotes. For example, this will
201 arguments are passed without parentheses or quotes. For example, this will
202 time the given statement::
202 time the given statement::
203
203
204 %timeit range(1000)
204 %timeit range(1000)
205
205
206 Cell magics are prefixed with a double %%, and they are functions that get as
206 Cell magics are prefixed with a double %%, and they are functions that get as
207 an argument not only the rest of the line, but also the lines below it in a
207 an argument not only the rest of the line, but also the lines below it in a
208 separate argument. These magics are called with two arguments: the rest of the
208 separate argument. These magics are called with two arguments: the rest of the
209 call line and the body of the cell, consisting of the lines below the first.
209 call line and the body of the cell, consisting of the lines below the first.
210 For example::
210 For example::
211
211
212 %%timeit x = numpy.random.randn((100, 100))
212 %%timeit x = numpy.random.randn((100, 100))
213 numpy.linalg.svd(x)
213 numpy.linalg.svd(x)
214
214
215 will time the execution of the numpy svd routine, running the assignment of x
215 will time the execution of the numpy svd routine, running the assignment of x
216 as part of the setup phase, which is not timed.
216 as part of the setup phase, which is not timed.
217
217
218 In a line-oriented client (the terminal or Qt console IPython), starting a new
218 In a line-oriented client (the terminal or Qt console IPython), starting a new
219 input with %% will automatically enter cell mode, and IPython will continue
219 input with %% will automatically enter cell mode, and IPython will continue
220 reading input until a blank line is given. In the notebook, simply type the
220 reading input until a blank line is given. In the notebook, simply type the
221 whole cell as one entity, but keep in mind that the %% escape can only be at
221 whole cell as one entity, but keep in mind that the %% escape can only be at
222 the very start of the cell.
222 the very start of the cell.
223
223
224 NOTE: If you have 'automagic' enabled (via the command line option or with the
224 NOTE: If you have 'automagic' enabled (via the command line option or with the
225 %automagic function), you don't need to type in the % explicitly for line
225 %automagic function), you don't need to type in the % explicitly for line
226 magics; cell magics always require an explicit '%%' escape. By default,
226 magics; cell magics always require an explicit '%%' escape. By default,
227 IPython ships with automagic on, so you should only rarely need the % escape.
227 IPython ships with automagic on, so you should only rarely need the % escape.
228
228
229 Example: typing '%cd mydir' (without the quotes) changes you working directory
229 Example: typing '%cd mydir' (without the quotes) changes you working directory
230 to 'mydir', if it exists.
230 to 'mydir', if it exists.
231
231
232 For a list of the available magic functions, use %lsmagic. For a description
232 For a list of the available magic functions, use %lsmagic. For a description
233 of any of them, type %magic_name?, e.g. '%cd?'.
233 of any of them, type %magic_name?, e.g. '%cd?'.
234
234
235 Currently the magic system has the following functions:""",
235 Currently the magic system has the following functions:""",
236 magic_docs,
236 magic_docs,
237 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
237 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
238 self._lsmagic(),
238 self._lsmagic(),
239 ]
239 ]
240 page.page('\n'.join(out))
240 page.page('\n'.join(out))
241
241
242
242
243 @line_magic
243 @line_magic
244 def page(self, parameter_s=''):
244 def page(self, parameter_s=''):
245 """Pretty print the object and display it through a pager.
245 """Pretty print the object and display it through a pager.
246
246
247 %page [options] OBJECT
247 %page [options] OBJECT
248
248
249 If no object is given, use _ (last output).
249 If no object is given, use _ (last output).
250
250
251 Options:
251 Options:
252
252
253 -r: page str(object), don't pretty-print it."""
253 -r: page str(object), don't pretty-print it."""
254
254
255 # After a function contributed by Olivier Aubert, slightly modified.
255 # After a function contributed by Olivier Aubert, slightly modified.
256
256
257 # Process options/args
257 # Process options/args
258 opts, args = self.parse_options(parameter_s, 'r')
258 opts, args = self.parse_options(parameter_s, 'r')
259 raw = 'r' in opts
259 raw = 'r' in opts
260
260
261 oname = args and args or '_'
261 oname = args and args or '_'
262 info = self.shell._ofind(oname)
262 info = self.shell._ofind(oname)
263 if info['found']:
263 if info['found']:
264 txt = (raw and str or pformat)( info['obj'] )
264 txt = (raw and str or pformat)( info['obj'] )
265 page.page(txt)
265 page.page(txt)
266 else:
266 else:
267 print('Object `%s` not found' % oname)
267 print('Object `%s` not found' % oname)
268
268
269 @line_magic
269 @line_magic
270 def profile(self, parameter_s=''):
270 def profile(self, parameter_s=''):
271 """Print your currently active IPython profile."""
271 """Print your currently active IPython profile."""
272 from IPython.core.application import BaseIPythonApplication
272 from IPython.core.application import BaseIPythonApplication
273 if BaseIPythonApplication.initialized():
273 if BaseIPythonApplication.initialized():
274 print(BaseIPythonApplication.instance().profile)
274 print(BaseIPythonApplication.instance().profile)
275 else:
275 else:
276 error("profile is an application-level value, but you don't appear to be in an IPython application")
276 error("profile is an application-level value, but you don't appear to be in an IPython application")
277
277
278 @line_magic
278 @line_magic
279 def pprint(self, parameter_s=''):
279 def pprint(self, parameter_s=''):
280 """Toggle pretty printing on/off."""
280 """Toggle pretty printing on/off."""
281 ptformatter = self.shell.display_formatter.formatters['text/plain']
281 ptformatter = self.shell.display_formatter.formatters['text/plain']
282 ptformatter.pprint = bool(1 - ptformatter.pprint)
282 ptformatter.pprint = bool(1 - ptformatter.pprint)
283 print('Pretty printing has been turned',
283 print('Pretty printing has been turned',
284 ['OFF','ON'][ptformatter.pprint])
284 ['OFF','ON'][ptformatter.pprint])
285
285
286 @line_magic
286 @line_magic
287 def colors(self, parameter_s=''):
287 def colors(self, parameter_s=''):
288 """Switch color scheme for prompts, info system and exception handlers.
288 """Switch color scheme for prompts, info system and exception handlers.
289
289
290 Currently implemented schemes: NoColor, Linux, LightBG.
290 Currently implemented schemes: NoColor, Linux, LightBG.
291
291
292 Color scheme names are not case-sensitive.
292 Color scheme names are not case-sensitive.
293
293
294 Examples
294 Examples
295 --------
295 --------
296 To get a plain black and white terminal::
296 To get a plain black and white terminal::
297
297
298 %colors nocolor
298 %colors nocolor
299 """
299 """
300 def color_switch_err(name):
300 def color_switch_err(name):
301 warn('Error changing %s color schemes.\n%s' %
301 warn('Error changing %s color schemes.\n%s' %
302 (name, sys.exc_info()[1]))
302 (name, sys.exc_info()[1]))
303
303
304
304
305 new_scheme = parameter_s.strip()
305 new_scheme = parameter_s.strip()
306 if not new_scheme:
306 if not new_scheme:
307 raise UsageError(
307 raise UsageError(
308 "%colors: you must specify a color scheme. See '%colors?'")
308 "%colors: you must specify a color scheme. See '%colors?'")
309 return
309 return
310 # local shortcut
310 # local shortcut
311 shell = self.shell
311 shell = self.shell
312
312
313 import IPython.utils.rlineimpl as readline
313 import IPython.utils.rlineimpl as readline
314
314
315 if not shell.colors_force and \
315 if not shell.colors_force and \
316 not readline.have_readline and \
316 not readline.have_readline and \
317 (sys.platform == "win32" or sys.platform == "cli"):
317 (sys.platform == "win32" or sys.platform == "cli"):
318 msg = """\
318 msg = """\
319 Proper color support under MS Windows requires the pyreadline library.
319 Proper color support under MS Windows requires the pyreadline library.
320 You can find it at:
320 You can find it at:
321 http://ipython.org/pyreadline.html
321 http://ipython.org/pyreadline.html
322 Gary's readline needs the ctypes module, from:
322 Gary's readline needs the ctypes module, from:
323 http://starship.python.net/crew/theller/ctypes
323 http://starship.python.net/crew/theller/ctypes
324 (Note that ctypes is already part of Python versions 2.5 and newer).
324 (Note that ctypes is already part of Python versions 2.5 and newer).
325
325
326 Defaulting color scheme to 'NoColor'"""
326 Defaulting color scheme to 'NoColor'"""
327 new_scheme = 'NoColor'
327 new_scheme = 'NoColor'
328 warn(msg)
328 warn(msg)
329
329
330 # readline option is 0
330 # readline option is 0
331 if not shell.colors_force and not shell.has_readline:
331 if not shell.colors_force and not shell.has_readline:
332 new_scheme = 'NoColor'
332 new_scheme = 'NoColor'
333
333
334 # Set prompt colors
334 # Set prompt colors
335 try:
335 try:
336 shell.prompt_manager.color_scheme = new_scheme
336 shell.prompt_manager.color_scheme = new_scheme
337 except:
337 except:
338 color_switch_err('prompt')
338 color_switch_err('prompt')
339 else:
339 else:
340 shell.colors = \
340 shell.colors = \
341 shell.prompt_manager.color_scheme_table.active_scheme_name
341 shell.prompt_manager.color_scheme_table.active_scheme_name
342 # Set exception colors
342 # Set exception colors
343 try:
343 try:
344 shell.InteractiveTB.set_colors(scheme = new_scheme)
344 shell.InteractiveTB.set_colors(scheme = new_scheme)
345 shell.SyntaxTB.set_colors(scheme = new_scheme)
345 shell.SyntaxTB.set_colors(scheme = new_scheme)
346 except:
346 except:
347 color_switch_err('exception')
347 color_switch_err('exception')
348
348
349 # Set info (for 'object?') colors
349 # Set info (for 'object?') colors
350 if shell.color_info:
350 if shell.color_info:
351 try:
351 try:
352 shell.inspector.set_active_scheme(new_scheme)
352 shell.inspector.set_active_scheme(new_scheme)
353 except:
353 except:
354 color_switch_err('object inspector')
354 color_switch_err('object inspector')
355 else:
355 else:
356 shell.inspector.set_active_scheme('NoColor')
356 shell.inspector.set_active_scheme('NoColor')
357
357
358 @line_magic
358 @line_magic
359 def xmode(self, parameter_s=''):
359 def xmode(self, parameter_s=''):
360 """Switch modes for the exception handlers.
360 """Switch modes for the exception handlers.
361
361
362 Valid modes: Plain, Context and Verbose.
362 Valid modes: Plain, Context and Verbose.
363
363
364 If called without arguments, acts as a toggle."""
364 If called without arguments, acts as a toggle."""
365
365
366 def xmode_switch_err(name):
366 def xmode_switch_err(name):
367 warn('Error changing %s exception modes.\n%s' %
367 warn('Error changing %s exception modes.\n%s' %
368 (name,sys.exc_info()[1]))
368 (name,sys.exc_info()[1]))
369
369
370 shell = self.shell
370 shell = self.shell
371 new_mode = parameter_s.strip().capitalize()
371 new_mode = parameter_s.strip().capitalize()
372 try:
372 try:
373 shell.InteractiveTB.set_mode(mode=new_mode)
373 shell.InteractiveTB.set_mode(mode=new_mode)
374 print('Exception reporting mode:',shell.InteractiveTB.mode)
374 print('Exception reporting mode:',shell.InteractiveTB.mode)
375 except:
375 except:
376 xmode_switch_err('user')
376 xmode_switch_err('user')
377
377
378 @line_magic
378 @line_magic
379 def quickref(self,arg):
379 def quickref(self,arg):
380 """ Show a quick reference sheet """
380 """ Show a quick reference sheet """
381 from IPython.core.usage import quick_reference
381 from IPython.core.usage import quick_reference
382 qr = quick_reference + self._magic_docs(brief=True)
382 qr = quick_reference + self._magic_docs(brief=True)
383 page.page(qr)
383 page.page(qr)
384
384
385 @line_magic
385 @line_magic
386 def doctest_mode(self, parameter_s=''):
386 def doctest_mode(self, parameter_s=''):
387 """Toggle doctest mode on and off.
387 """Toggle doctest mode on and off.
388
388
389 This mode is intended to make IPython behave as much as possible like a
389 This mode is intended to make IPython behave as much as possible like a
390 plain Python shell, from the perspective of how its prompts, exceptions
390 plain Python shell, from the perspective of how its prompts, exceptions
391 and output look. This makes it easy to copy and paste parts of a
391 and output look. This makes it easy to copy and paste parts of a
392 session into doctests. It does so by:
392 session into doctests. It does so by:
393
393
394 - Changing the prompts to the classic ``>>>`` ones.
394 - Changing the prompts to the classic ``>>>`` ones.
395 - Changing the exception reporting mode to 'Plain'.
395 - Changing the exception reporting mode to 'Plain'.
396 - Disabling pretty-printing of output.
396 - Disabling pretty-printing of output.
397
397
398 Note that IPython also supports the pasting of code snippets that have
398 Note that IPython also supports the pasting of code snippets that have
399 leading '>>>' and '...' prompts in them. This means that you can paste
399 leading '>>>' and '...' prompts in them. This means that you can paste
400 doctests from files or docstrings (even if they have leading
400 doctests from files or docstrings (even if they have leading
401 whitespace), and the code will execute correctly. You can then use
401 whitespace), and the code will execute correctly. You can then use
402 '%history -t' to see the translated history; this will give you the
402 '%history -t' to see the translated history; this will give you the
403 input after removal of all the leading prompts and whitespace, which
403 input after removal of all the leading prompts and whitespace, which
404 can be pasted back into an editor.
404 can be pasted back into an editor.
405
405
406 With these features, you can switch into this mode easily whenever you
406 With these features, you can switch into this mode easily whenever you
407 need to do testing and changes to doctests, without having to leave
407 need to do testing and changes to doctests, without having to leave
408 your existing IPython session.
408 your existing IPython session.
409 """
409 """
410
410
411 # Shorthands
411 # Shorthands
412 shell = self.shell
412 shell = self.shell
413 pm = shell.prompt_manager
413 pm = shell.prompt_manager
414 meta = shell.meta
414 meta = shell.meta
415 disp_formatter = self.shell.display_formatter
415 disp_formatter = self.shell.display_formatter
416 ptformatter = disp_formatter.formatters['text/plain']
416 ptformatter = disp_formatter.formatters['text/plain']
417 # dstore is a data store kept in the instance metadata bag to track any
417 # dstore is a data store kept in the instance metadata bag to track any
418 # changes we make, so we can undo them later.
418 # changes we make, so we can undo them later.
419 dstore = meta.setdefault('doctest_mode',Struct())
419 dstore = meta.setdefault('doctest_mode',Struct())
420 save_dstore = dstore.setdefault
420 save_dstore = dstore.setdefault
421
421
422 # save a few values we'll need to recover later
422 # save a few values we'll need to recover later
423 mode = save_dstore('mode',False)
423 mode = save_dstore('mode',False)
424 save_dstore('rc_pprint',ptformatter.pprint)
424 save_dstore('rc_pprint',ptformatter.pprint)
425 save_dstore('xmode',shell.InteractiveTB.mode)
425 save_dstore('xmode',shell.InteractiveTB.mode)
426 save_dstore('rc_separate_out',shell.separate_out)
426 save_dstore('rc_separate_out',shell.separate_out)
427 save_dstore('rc_separate_out2',shell.separate_out2)
427 save_dstore('rc_separate_out2',shell.separate_out2)
428 save_dstore('rc_prompts_pad_left',pm.justify)
428 save_dstore('rc_prompts_pad_left',pm.justify)
429 save_dstore('rc_separate_in',shell.separate_in)
429 save_dstore('rc_separate_in',shell.separate_in)
430 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
430 save_dstore('rc_active_types',disp_formatter.active_types)
431 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
431 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
432
432
433 if mode == False:
433 if mode == False:
434 # turn on
434 # turn on
435 pm.in_template = '>>> '
435 pm.in_template = '>>> '
436 pm.in2_template = '... '
436 pm.in2_template = '... '
437 pm.out_template = ''
437 pm.out_template = ''
438
438
439 # Prompt separators like plain python
439 # Prompt separators like plain python
440 shell.separate_in = ''
440 shell.separate_in = ''
441 shell.separate_out = ''
441 shell.separate_out = ''
442 shell.separate_out2 = ''
442 shell.separate_out2 = ''
443
443
444 pm.justify = False
444 pm.justify = False
445
445
446 ptformatter.pprint = False
446 ptformatter.pprint = False
447 disp_formatter.plain_text_only = True
447 disp_formatter.active_types = ['text/plain']
448
448
449 shell.magic('xmode Plain')
449 shell.magic('xmode Plain')
450 else:
450 else:
451 # turn off
451 # turn off
452 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
452 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
453
453
454 shell.separate_in = dstore.rc_separate_in
454 shell.separate_in = dstore.rc_separate_in
455
455
456 shell.separate_out = dstore.rc_separate_out
456 shell.separate_out = dstore.rc_separate_out
457 shell.separate_out2 = dstore.rc_separate_out2
457 shell.separate_out2 = dstore.rc_separate_out2
458
458
459 pm.justify = dstore.rc_prompts_pad_left
459 pm.justify = dstore.rc_prompts_pad_left
460
460
461 ptformatter.pprint = dstore.rc_pprint
461 ptformatter.pprint = dstore.rc_pprint
462 disp_formatter.plain_text_only = dstore.rc_plain_text_only
462 disp_formatter.active_types = dstore.rc_active_types
463
463
464 shell.magic('xmode ' + dstore.xmode)
464 shell.magic('xmode ' + dstore.xmode)
465
465
466 # Store new mode and inform
466 # Store new mode and inform
467 dstore.mode = bool(1-int(mode))
467 dstore.mode = bool(1-int(mode))
468 mode_label = ['OFF','ON'][dstore.mode]
468 mode_label = ['OFF','ON'][dstore.mode]
469 print('Doctest mode is:', mode_label)
469 print('Doctest mode is:', mode_label)
470
470
471 @line_magic
471 @line_magic
472 def gui(self, parameter_s=''):
472 def gui(self, parameter_s=''):
473 """Enable or disable IPython GUI event loop integration.
473 """Enable or disable IPython GUI event loop integration.
474
474
475 %gui [GUINAME]
475 %gui [GUINAME]
476
476
477 This magic replaces IPython's threaded shells that were activated
477 This magic replaces IPython's threaded shells that were activated
478 using the (pylab/wthread/etc.) command line flags. GUI toolkits
478 using the (pylab/wthread/etc.) command line flags. GUI toolkits
479 can now be enabled at runtime and keyboard
479 can now be enabled at runtime and keyboard
480 interrupts should work without any problems. The following toolkits
480 interrupts should work without any problems. The following toolkits
481 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
481 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
482
482
483 %gui wx # enable wxPython event loop integration
483 %gui wx # enable wxPython event loop integration
484 %gui qt4|qt # enable PyQt4 event loop integration
484 %gui qt4|qt # enable PyQt4 event loop integration
485 %gui gtk # enable PyGTK event loop integration
485 %gui gtk # enable PyGTK event loop integration
486 %gui gtk3 # enable Gtk3 event loop integration
486 %gui gtk3 # enable Gtk3 event loop integration
487 %gui tk # enable Tk event loop integration
487 %gui tk # enable Tk event loop integration
488 %gui osx # enable Cocoa event loop integration
488 %gui osx # enable Cocoa event loop integration
489 # (requires %matplotlib 1.1)
489 # (requires %matplotlib 1.1)
490 %gui # disable all event loop integration
490 %gui # disable all event loop integration
491
491
492 WARNING: after any of these has been called you can simply create
492 WARNING: after any of these has been called you can simply create
493 an application object, but DO NOT start the event loop yourself, as
493 an application object, but DO NOT start the event loop yourself, as
494 we have already handled that.
494 we have already handled that.
495 """
495 """
496 opts, arg = self.parse_options(parameter_s, '')
496 opts, arg = self.parse_options(parameter_s, '')
497 if arg=='': arg = None
497 if arg=='': arg = None
498 try:
498 try:
499 return self.shell.enable_gui(arg)
499 return self.shell.enable_gui(arg)
500 except Exception as e:
500 except Exception as e:
501 # print simple error message, rather than traceback if we can't
501 # print simple error message, rather than traceback if we can't
502 # hook up the GUI
502 # hook up the GUI
503 error(str(e))
503 error(str(e))
504
504
505 @skip_doctest
505 @skip_doctest
506 @line_magic
506 @line_magic
507 def precision(self, s=''):
507 def precision(self, s=''):
508 """Set floating point precision for pretty printing.
508 """Set floating point precision for pretty printing.
509
509
510 Can set either integer precision or a format string.
510 Can set either integer precision or a format string.
511
511
512 If numpy has been imported and precision is an int,
512 If numpy has been imported and precision is an int,
513 numpy display precision will also be set, via ``numpy.set_printoptions``.
513 numpy display precision will also be set, via ``numpy.set_printoptions``.
514
514
515 If no argument is given, defaults will be restored.
515 If no argument is given, defaults will be restored.
516
516
517 Examples
517 Examples
518 --------
518 --------
519 ::
519 ::
520
520
521 In [1]: from math import pi
521 In [1]: from math import pi
522
522
523 In [2]: %precision 3
523 In [2]: %precision 3
524 Out[2]: u'%.3f'
524 Out[2]: u'%.3f'
525
525
526 In [3]: pi
526 In [3]: pi
527 Out[3]: 3.142
527 Out[3]: 3.142
528
528
529 In [4]: %precision %i
529 In [4]: %precision %i
530 Out[4]: u'%i'
530 Out[4]: u'%i'
531
531
532 In [5]: pi
532 In [5]: pi
533 Out[5]: 3
533 Out[5]: 3
534
534
535 In [6]: %precision %e
535 In [6]: %precision %e
536 Out[6]: u'%e'
536 Out[6]: u'%e'
537
537
538 In [7]: pi**10
538 In [7]: pi**10
539 Out[7]: 9.364805e+04
539 Out[7]: 9.364805e+04
540
540
541 In [8]: %precision
541 In [8]: %precision
542 Out[8]: u'%r'
542 Out[8]: u'%r'
543
543
544 In [9]: pi**10
544 In [9]: pi**10
545 Out[9]: 93648.047476082982
545 Out[9]: 93648.047476082982
546 """
546 """
547 ptformatter = self.shell.display_formatter.formatters['text/plain']
547 ptformatter = self.shell.display_formatter.formatters['text/plain']
548 ptformatter.float_precision = s
548 ptformatter.float_precision = s
549 return ptformatter.float_format
549 return ptformatter.float_format
550
550
551 @magic_arguments.magic_arguments()
551 @magic_arguments.magic_arguments()
552 @magic_arguments.argument(
552 @magic_arguments.argument(
553 '-e', '--export', action='store_true', default=False,
553 '-e', '--export', action='store_true', default=False,
554 help='Export IPython history as a notebook. The filename argument '
554 help='Export IPython history as a notebook. The filename argument '
555 'is used to specify the notebook name and format. For example '
555 'is used to specify the notebook name and format. For example '
556 'a filename of notebook.ipynb will result in a notebook name '
556 'a filename of notebook.ipynb will result in a notebook name '
557 'of "notebook" and a format of "xml". Likewise using a ".json" '
557 'of "notebook" and a format of "xml". Likewise using a ".json" '
558 'or ".py" file extension will write the notebook in the json '
558 'or ".py" file extension will write the notebook in the json '
559 'or py formats.'
559 'or py formats.'
560 )
560 )
561 @magic_arguments.argument(
561 @magic_arguments.argument(
562 '-f', '--format',
562 '-f', '--format',
563 help='Convert an existing IPython notebook to a new format. This option '
563 help='Convert an existing IPython notebook to a new format. This option '
564 'specifies the new format and can have the values: xml, json, py. '
564 'specifies the new format and can have the values: xml, json, py. '
565 'The target filename is chosen automatically based on the new '
565 'The target filename is chosen automatically based on the new '
566 'format. The filename argument gives the name of the source file.'
566 'format. The filename argument gives the name of the source file.'
567 )
567 )
568 @magic_arguments.argument(
568 @magic_arguments.argument(
569 'filename', type=unicode,
569 'filename', type=unicode,
570 help='Notebook name or filename'
570 help='Notebook name or filename'
571 )
571 )
572 @line_magic
572 @line_magic
573 def notebook(self, s):
573 def notebook(self, s):
574 """Export and convert IPython notebooks.
574 """Export and convert IPython notebooks.
575
575
576 This function can export the current IPython history to a notebook file
576 This function can export the current IPython history to a notebook file
577 or can convert an existing notebook file into a different format. For
577 or can convert an existing notebook file into a different format. For
578 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
578 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
579 To export the history to "foo.py" do "%notebook -e foo.py". To convert
579 To export the history to "foo.py" do "%notebook -e foo.py". To convert
580 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
580 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
581 formats include (json/ipynb, py).
581 formats include (json/ipynb, py).
582 """
582 """
583 args = magic_arguments.parse_argstring(self.notebook, s)
583 args = magic_arguments.parse_argstring(self.notebook, s)
584
584
585 from IPython.nbformat import current
585 from IPython.nbformat import current
586 args.filename = unquote_filename(args.filename)
586 args.filename = unquote_filename(args.filename)
587 if args.export:
587 if args.export:
588 fname, name, format = current.parse_filename(args.filename)
588 fname, name, format = current.parse_filename(args.filename)
589 cells = []
589 cells = []
590 hist = list(self.shell.history_manager.get_range())
590 hist = list(self.shell.history_manager.get_range())
591 for session, prompt_number, input in hist[:-1]:
591 for session, prompt_number, input in hist[:-1]:
592 cells.append(current.new_code_cell(prompt_number=prompt_number,
592 cells.append(current.new_code_cell(prompt_number=prompt_number,
593 input=input))
593 input=input))
594 worksheet = current.new_worksheet(cells=cells)
594 worksheet = current.new_worksheet(cells=cells)
595 nb = current.new_notebook(name=name,worksheets=[worksheet])
595 nb = current.new_notebook(name=name,worksheets=[worksheet])
596 with io.open(fname, 'w', encoding='utf-8') as f:
596 with io.open(fname, 'w', encoding='utf-8') as f:
597 current.write(nb, f, format);
597 current.write(nb, f, format);
598 elif args.format is not None:
598 elif args.format is not None:
599 old_fname, old_name, old_format = current.parse_filename(args.filename)
599 old_fname, old_name, old_format = current.parse_filename(args.filename)
600 new_format = args.format
600 new_format = args.format
601 if new_format == u'xml':
601 if new_format == u'xml':
602 raise ValueError('Notebooks cannot be written as xml.')
602 raise ValueError('Notebooks cannot be written as xml.')
603 elif new_format == u'ipynb' or new_format == u'json':
603 elif new_format == u'ipynb' or new_format == u'json':
604 new_fname = old_name + u'.ipynb'
604 new_fname = old_name + u'.ipynb'
605 new_format = u'json'
605 new_format = u'json'
606 elif new_format == u'py':
606 elif new_format == u'py':
607 new_fname = old_name + u'.py'
607 new_fname = old_name + u'.py'
608 else:
608 else:
609 raise ValueError('Invalid notebook format: %s' % new_format)
609 raise ValueError('Invalid notebook format: %s' % new_format)
610 with io.open(old_fname, 'r', encoding='utf-8') as f:
610 with io.open(old_fname, 'r', encoding='utf-8') as f:
611 nb = current.read(f, old_format)
611 nb = current.read(f, old_format)
612 with io.open(new_fname, 'w', encoding='utf-8') as f:
612 with io.open(new_fname, 'w', encoding='utf-8') as f:
613 current.write(nb, f, new_format)
613 current.write(nb, f, new_format)
@@ -1,591 +1,591 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 os
19 import os
20 import sys
20 import sys
21 import time
21 import time
22
22
23 # System library imports
23 # System library imports
24 from zmq.eventloop import ioloop
24 from zmq.eventloop import ioloop
25
25
26 # Our own
26 # Our own
27 from IPython.core.interactiveshell import (
27 from IPython.core.interactiveshell import (
28 InteractiveShell, InteractiveShellABC
28 InteractiveShell, InteractiveShellABC
29 )
29 )
30 from IPython.core import page
30 from IPython.core import page
31 from IPython.core.autocall import ZMQExitAutocall
31 from IPython.core.autocall import ZMQExitAutocall
32 from IPython.core.displaypub import DisplayPublisher
32 from IPython.core.displaypub import DisplayPublisher
33 from IPython.core.error import UsageError
33 from IPython.core.error import UsageError
34 from IPython.core.magics import MacroToEdit, CodeMagics
34 from IPython.core.magics import MacroToEdit, CodeMagics
35 from IPython.core.magic import magics_class, line_magic, Magics
35 from IPython.core.magic import magics_class, line_magic, Magics
36 from IPython.core.payloadpage import install_payload_page
36 from IPython.core.payloadpage import install_payload_page
37 from IPython.kernel.inprocess.socket import SocketABC
37 from IPython.kernel.inprocess.socket import SocketABC
38 from IPython.kernel import (
38 from IPython.kernel import (
39 get_connection_file, get_connection_info, connect_qtconsole
39 get_connection_file, get_connection_info, connect_qtconsole
40 )
40 )
41 from IPython.testing.skipdoctest import skip_doctest
41 from IPython.testing.skipdoctest import skip_doctest
42 from IPython.utils import io, openpy
42 from IPython.utils import io, openpy
43 from IPython.utils.jsonutil import json_clean, encode_images
43 from IPython.utils.jsonutil import json_clean, encode_images
44 from IPython.utils.process import arg_split
44 from IPython.utils.process import arg_split
45 from IPython.utils import py3compat
45 from IPython.utils import py3compat
46 from IPython.utils.traitlets import Instance, Type, Dict, CBool, CBytes
46 from IPython.utils.traitlets import Instance, Type, Dict, CBool, CBytes
47 from IPython.utils.warn import warn, error
47 from IPython.utils.warn import warn, error
48 from IPython.kernel.zmq.displayhook import ZMQShellDisplayHook
48 from IPython.kernel.zmq.displayhook import ZMQShellDisplayHook
49 from IPython.kernel.zmq.datapub import ZMQDataPublisher
49 from IPython.kernel.zmq.datapub import ZMQDataPublisher
50 from IPython.kernel.zmq.session import extract_header
50 from IPython.kernel.zmq.session import extract_header
51 from session import Session
51 from session import Session
52
52
53 #-----------------------------------------------------------------------------
53 #-----------------------------------------------------------------------------
54 # Functions and classes
54 # Functions and classes
55 #-----------------------------------------------------------------------------
55 #-----------------------------------------------------------------------------
56
56
57 class ZMQDisplayPublisher(DisplayPublisher):
57 class ZMQDisplayPublisher(DisplayPublisher):
58 """A display publisher that publishes data using a ZeroMQ PUB socket."""
58 """A display publisher that publishes data using a ZeroMQ PUB socket."""
59
59
60 session = Instance(Session)
60 session = Instance(Session)
61 pub_socket = Instance(SocketABC)
61 pub_socket = Instance(SocketABC)
62 parent_header = Dict({})
62 parent_header = Dict({})
63 topic = CBytes(b'displaypub')
63 topic = CBytes(b'displaypub')
64
64
65 def set_parent(self, parent):
65 def set_parent(self, parent):
66 """Set the parent for outbound messages."""
66 """Set the parent for outbound messages."""
67 self.parent_header = extract_header(parent)
67 self.parent_header = extract_header(parent)
68
68
69 def _flush_streams(self):
69 def _flush_streams(self):
70 """flush IO Streams prior to display"""
70 """flush IO Streams prior to display"""
71 sys.stdout.flush()
71 sys.stdout.flush()
72 sys.stderr.flush()
72 sys.stderr.flush()
73
73
74 def publish(self, source, data, metadata=None):
74 def publish(self, source, data, metadata=None):
75 self._flush_streams()
75 self._flush_streams()
76 if metadata is None:
76 if metadata is None:
77 metadata = {}
77 metadata = {}
78 self._validate_data(source, data, metadata)
78 self._validate_data(source, data, metadata)
79 content = {}
79 content = {}
80 content['source'] = source
80 content['source'] = source
81 content['data'] = encode_images(data)
81 content['data'] = encode_images(data)
82 content['metadata'] = metadata
82 content['metadata'] = metadata
83 self.session.send(
83 self.session.send(
84 self.pub_socket, u'display_data', json_clean(content),
84 self.pub_socket, u'display_data', json_clean(content),
85 parent=self.parent_header, ident=self.topic,
85 parent=self.parent_header, ident=self.topic,
86 )
86 )
87
87
88 def clear_output(self, stdout=True, stderr=True, other=True):
88 def clear_output(self, stdout=True, stderr=True, other=True):
89 content = dict(stdout=stdout, stderr=stderr, other=other)
89 content = dict(stdout=stdout, stderr=stderr, other=other)
90
90
91 if stdout:
91 if stdout:
92 print('\r', file=sys.stdout, end='')
92 print('\r', file=sys.stdout, end='')
93 if stderr:
93 if stderr:
94 print('\r', file=sys.stderr, end='')
94 print('\r', file=sys.stderr, end='')
95
95
96 self._flush_streams()
96 self._flush_streams()
97
97
98 self.session.send(
98 self.session.send(
99 self.pub_socket, u'clear_output', content,
99 self.pub_socket, u'clear_output', content,
100 parent=self.parent_header, ident=self.topic,
100 parent=self.parent_header, ident=self.topic,
101 )
101 )
102
102
103 @magics_class
103 @magics_class
104 class KernelMagics(Magics):
104 class KernelMagics(Magics):
105 #------------------------------------------------------------------------
105 #------------------------------------------------------------------------
106 # Magic overrides
106 # Magic overrides
107 #------------------------------------------------------------------------
107 #------------------------------------------------------------------------
108 # Once the base class stops inheriting from magic, this code needs to be
108 # Once the base class stops inheriting from magic, this code needs to be
109 # moved into a separate machinery as well. For now, at least isolate here
109 # moved into a separate machinery as well. For now, at least isolate here
110 # the magics which this class needs to implement differently from the base
110 # the magics which this class needs to implement differently from the base
111 # class, or that are unique to it.
111 # class, or that are unique to it.
112
112
113 @line_magic
113 @line_magic
114 def doctest_mode(self, parameter_s=''):
114 def doctest_mode(self, parameter_s=''):
115 """Toggle doctest mode on and off.
115 """Toggle doctest mode on and off.
116
116
117 This mode is intended to make IPython behave as much as possible like a
117 This mode is intended to make IPython behave as much as possible like a
118 plain Python shell, from the perspective of how its prompts, exceptions
118 plain Python shell, from the perspective of how its prompts, exceptions
119 and output look. This makes it easy to copy and paste parts of a
119 and output look. This makes it easy to copy and paste parts of a
120 session into doctests. It does so by:
120 session into doctests. It does so by:
121
121
122 - Changing the prompts to the classic ``>>>`` ones.
122 - Changing the prompts to the classic ``>>>`` ones.
123 - Changing the exception reporting mode to 'Plain'.
123 - Changing the exception reporting mode to 'Plain'.
124 - Disabling pretty-printing of output.
124 - Disabling pretty-printing of output.
125
125
126 Note that IPython also supports the pasting of code snippets that have
126 Note that IPython also supports the pasting of code snippets that have
127 leading '>>>' and '...' prompts in them. This means that you can paste
127 leading '>>>' and '...' prompts in them. This means that you can paste
128 doctests from files or docstrings (even if they have leading
128 doctests from files or docstrings (even if they have leading
129 whitespace), and the code will execute correctly. You can then use
129 whitespace), and the code will execute correctly. You can then use
130 '%history -t' to see the translated history; this will give you the
130 '%history -t' to see the translated history; this will give you the
131 input after removal of all the leading prompts and whitespace, which
131 input after removal of all the leading prompts and whitespace, which
132 can be pasted back into an editor.
132 can be pasted back into an editor.
133
133
134 With these features, you can switch into this mode easily whenever you
134 With these features, you can switch into this mode easily whenever you
135 need to do testing and changes to doctests, without having to leave
135 need to do testing and changes to doctests, without having to leave
136 your existing IPython session.
136 your existing IPython session.
137 """
137 """
138
138
139 from IPython.utils.ipstruct import Struct
139 from IPython.utils.ipstruct import Struct
140
140
141 # Shorthands
141 # Shorthands
142 shell = self.shell
142 shell = self.shell
143 disp_formatter = self.shell.display_formatter
143 disp_formatter = self.shell.display_formatter
144 ptformatter = disp_formatter.formatters['text/plain']
144 ptformatter = disp_formatter.formatters['text/plain']
145 # dstore is a data store kept in the instance metadata bag to track any
145 # dstore is a data store kept in the instance metadata bag to track any
146 # changes we make, so we can undo them later.
146 # changes we make, so we can undo them later.
147 dstore = shell.meta.setdefault('doctest_mode', Struct())
147 dstore = shell.meta.setdefault('doctest_mode', Struct())
148 save_dstore = dstore.setdefault
148 save_dstore = dstore.setdefault
149
149
150 # save a few values we'll need to recover later
150 # save a few values we'll need to recover later
151 mode = save_dstore('mode', False)
151 mode = save_dstore('mode', False)
152 save_dstore('rc_pprint', ptformatter.pprint)
152 save_dstore('rc_pprint', ptformatter.pprint)
153 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
153 save_dstore('rc_active_types',disp_formatter.active_types)
154 save_dstore('xmode', shell.InteractiveTB.mode)
154 save_dstore('xmode', shell.InteractiveTB.mode)
155
155
156 if mode == False:
156 if mode == False:
157 # turn on
157 # turn on
158 ptformatter.pprint = False
158 ptformatter.pprint = False
159 disp_formatter.plain_text_only = True
159 disp_formatter.active_types = ['text/plain']
160 shell.magic('xmode Plain')
160 shell.magic('xmode Plain')
161 else:
161 else:
162 # turn off
162 # turn off
163 ptformatter.pprint = dstore.rc_pprint
163 ptformatter.pprint = dstore.rc_pprint
164 disp_formatter.plain_text_only = dstore.rc_plain_text_only
164 disp_formatter.active_types = dstore.rc_active_types
165 shell.magic("xmode " + dstore.xmode)
165 shell.magic("xmode " + dstore.xmode)
166
166
167 # Store new mode and inform on console
167 # Store new mode and inform on console
168 dstore.mode = bool(1-int(mode))
168 dstore.mode = bool(1-int(mode))
169 mode_label = ['OFF','ON'][dstore.mode]
169 mode_label = ['OFF','ON'][dstore.mode]
170 print('Doctest mode is:', mode_label)
170 print('Doctest mode is:', mode_label)
171
171
172 # Send the payload back so that clients can modify their prompt display
172 # Send the payload back so that clients can modify their prompt display
173 payload = dict(
173 payload = dict(
174 source='IPython.kernel.zmq.zmqshell.ZMQInteractiveShell.doctest_mode',
174 source='IPython.kernel.zmq.zmqshell.ZMQInteractiveShell.doctest_mode',
175 mode=dstore.mode)
175 mode=dstore.mode)
176 shell.payload_manager.write_payload(payload)
176 shell.payload_manager.write_payload(payload)
177
177
178
178
179 _find_edit_target = CodeMagics._find_edit_target
179 _find_edit_target = CodeMagics._find_edit_target
180
180
181 @skip_doctest
181 @skip_doctest
182 @line_magic
182 @line_magic
183 def edit(self, parameter_s='', last_call=['','']):
183 def edit(self, parameter_s='', last_call=['','']):
184 """Bring up an editor and execute the resulting code.
184 """Bring up an editor and execute the resulting code.
185
185
186 Usage:
186 Usage:
187 %edit [options] [args]
187 %edit [options] [args]
188
188
189 %edit runs an external text editor. You will need to set the command for
189 %edit runs an external text editor. You will need to set the command for
190 this editor via the ``TerminalInteractiveShell.editor`` option in your
190 this editor via the ``TerminalInteractiveShell.editor`` option in your
191 configuration file before it will work.
191 configuration file before it will work.
192
192
193 This command allows you to conveniently edit multi-line code right in
193 This command allows you to conveniently edit multi-line code right in
194 your IPython session.
194 your IPython session.
195
195
196 If called without arguments, %edit opens up an empty editor with a
196 If called without arguments, %edit opens up an empty editor with a
197 temporary file and will execute the contents of this file when you
197 temporary file and will execute the contents of this file when you
198 close it (don't forget to save it!).
198 close it (don't forget to save it!).
199
199
200
200
201 Options:
201 Options:
202
202
203 -n <number>: open the editor at a specified line number. By default,
203 -n <number>: open the editor at a specified line number. By default,
204 the IPython editor hook uses the unix syntax 'editor +N filename', but
204 the IPython editor hook uses the unix syntax 'editor +N filename', but
205 you can configure this by providing your own modified hook if your
205 you can configure this by providing your own modified hook if your
206 favorite editor supports line-number specifications with a different
206 favorite editor supports line-number specifications with a different
207 syntax.
207 syntax.
208
208
209 -p: this will call the editor with the same data as the previous time
209 -p: this will call the editor with the same data as the previous time
210 it was used, regardless of how long ago (in your current session) it
210 it was used, regardless of how long ago (in your current session) it
211 was.
211 was.
212
212
213 -r: use 'raw' input. This option only applies to input taken from the
213 -r: use 'raw' input. This option only applies to input taken from the
214 user's history. By default, the 'processed' history is used, so that
214 user's history. By default, the 'processed' history is used, so that
215 magics are loaded in their transformed version to valid Python. If
215 magics are loaded in their transformed version to valid Python. If
216 this option is given, the raw input as typed as the command line is
216 this option is given, the raw input as typed as the command line is
217 used instead. When you exit the editor, it will be executed by
217 used instead. When you exit the editor, it will be executed by
218 IPython's own processor.
218 IPython's own processor.
219
219
220 -x: do not execute the edited code immediately upon exit. This is
220 -x: do not execute the edited code immediately upon exit. This is
221 mainly useful if you are editing programs which need to be called with
221 mainly useful if you are editing programs which need to be called with
222 command line arguments, which you can then do using %run.
222 command line arguments, which you can then do using %run.
223
223
224
224
225 Arguments:
225 Arguments:
226
226
227 If arguments are given, the following possibilites exist:
227 If arguments are given, the following possibilites exist:
228
228
229 - The arguments are numbers or pairs of colon-separated numbers (like
229 - The arguments are numbers or pairs of colon-separated numbers (like
230 1 4:8 9). These are interpreted as lines of previous input to be
230 1 4:8 9). These are interpreted as lines of previous input to be
231 loaded into the editor. The syntax is the same of the %macro command.
231 loaded into the editor. The syntax is the same of the %macro command.
232
232
233 - If the argument doesn't start with a number, it is evaluated as a
233 - If the argument doesn't start with a number, it is evaluated as a
234 variable and its contents loaded into the editor. You can thus edit
234 variable and its contents loaded into the editor. You can thus edit
235 any string which contains python code (including the result of
235 any string which contains python code (including the result of
236 previous edits).
236 previous edits).
237
237
238 - If the argument is the name of an object (other than a string),
238 - If the argument is the name of an object (other than a string),
239 IPython will try to locate the file where it was defined and open the
239 IPython will try to locate the file where it was defined and open the
240 editor at the point where it is defined. You can use `%edit function`
240 editor at the point where it is defined. You can use `%edit function`
241 to load an editor exactly at the point where 'function' is defined,
241 to load an editor exactly at the point where 'function' is defined,
242 edit it and have the file be executed automatically.
242 edit it and have the file be executed automatically.
243
243
244 If the object is a macro (see %macro for details), this opens up your
244 If the object is a macro (see %macro for details), this opens up your
245 specified editor with a temporary file containing the macro's data.
245 specified editor with a temporary file containing the macro's data.
246 Upon exit, the macro is reloaded with the contents of the file.
246 Upon exit, the macro is reloaded with the contents of the file.
247
247
248 Note: opening at an exact line is only supported under Unix, and some
248 Note: opening at an exact line is only supported under Unix, and some
249 editors (like kedit and gedit up to Gnome 2.8) do not understand the
249 editors (like kedit and gedit up to Gnome 2.8) do not understand the
250 '+NUMBER' parameter necessary for this feature. Good editors like
250 '+NUMBER' parameter necessary for this feature. Good editors like
251 (X)Emacs, vi, jed, pico and joe all do.
251 (X)Emacs, vi, jed, pico and joe all do.
252
252
253 - If the argument is not found as a variable, IPython will look for a
253 - If the argument is not found as a variable, IPython will look for a
254 file with that name (adding .py if necessary) and load it into the
254 file with that name (adding .py if necessary) and load it into the
255 editor. It will execute its contents with execfile() when you exit,
255 editor. It will execute its contents with execfile() when you exit,
256 loading any code in the file into your interactive namespace.
256 loading any code in the file into your interactive namespace.
257
257
258 After executing your code, %edit will return as output the code you
258 After executing your code, %edit will return as output the code you
259 typed in the editor (except when it was an existing file). This way
259 typed in the editor (except when it was an existing file). This way
260 you can reload the code in further invocations of %edit as a variable,
260 you can reload the code in further invocations of %edit as a variable,
261 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
261 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
262 the output.
262 the output.
263
263
264 Note that %edit is also available through the alias %ed.
264 Note that %edit is also available through the alias %ed.
265
265
266 This is an example of creating a simple function inside the editor and
266 This is an example of creating a simple function inside the editor and
267 then modifying it. First, start up the editor:
267 then modifying it. First, start up the editor:
268
268
269 In [1]: ed
269 In [1]: ed
270 Editing... done. Executing edited code...
270 Editing... done. Executing edited code...
271 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
271 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
272
272
273 We can then call the function foo():
273 We can then call the function foo():
274
274
275 In [2]: foo()
275 In [2]: foo()
276 foo() was defined in an editing session
276 foo() was defined in an editing session
277
277
278 Now we edit foo. IPython automatically loads the editor with the
278 Now we edit foo. IPython automatically loads the editor with the
279 (temporary) file where foo() was previously defined:
279 (temporary) file where foo() was previously defined:
280
280
281 In [3]: ed foo
281 In [3]: ed foo
282 Editing... done. Executing edited code...
282 Editing... done. Executing edited code...
283
283
284 And if we call foo() again we get the modified version:
284 And if we call foo() again we get the modified version:
285
285
286 In [4]: foo()
286 In [4]: foo()
287 foo() has now been changed!
287 foo() has now been changed!
288
288
289 Here is an example of how to edit a code snippet successive
289 Here is an example of how to edit a code snippet successive
290 times. First we call the editor:
290 times. First we call the editor:
291
291
292 In [5]: ed
292 In [5]: ed
293 Editing... done. Executing edited code...
293 Editing... done. Executing edited code...
294 hello
294 hello
295 Out[5]: "print 'hello'n"
295 Out[5]: "print 'hello'n"
296
296
297 Now we call it again with the previous output (stored in _):
297 Now we call it again with the previous output (stored in _):
298
298
299 In [6]: ed _
299 In [6]: ed _
300 Editing... done. Executing edited code...
300 Editing... done. Executing edited code...
301 hello world
301 hello world
302 Out[6]: "print 'hello world'n"
302 Out[6]: "print 'hello world'n"
303
303
304 Now we call it with the output #8 (stored in _8, also as Out[8]):
304 Now we call it with the output #8 (stored in _8, also as Out[8]):
305
305
306 In [7]: ed _8
306 In [7]: ed _8
307 Editing... done. Executing edited code...
307 Editing... done. Executing edited code...
308 hello again
308 hello again
309 Out[7]: "print 'hello again'n"
309 Out[7]: "print 'hello again'n"
310 """
310 """
311
311
312 opts,args = self.parse_options(parameter_s,'prn:')
312 opts,args = self.parse_options(parameter_s,'prn:')
313
313
314 try:
314 try:
315 filename, lineno, _ = CodeMagics._find_edit_target(self.shell, args, opts, last_call)
315 filename, lineno, _ = CodeMagics._find_edit_target(self.shell, args, opts, last_call)
316 except MacroToEdit as e:
316 except MacroToEdit as e:
317 # TODO: Implement macro editing over 2 processes.
317 # TODO: Implement macro editing over 2 processes.
318 print("Macro editing not yet implemented in 2-process model.")
318 print("Macro editing not yet implemented in 2-process model.")
319 return
319 return
320
320
321 # Make sure we send to the client an absolute path, in case the working
321 # Make sure we send to the client an absolute path, in case the working
322 # directory of client and kernel don't match
322 # directory of client and kernel don't match
323 filename = os.path.abspath(filename)
323 filename = os.path.abspath(filename)
324
324
325 payload = {
325 payload = {
326 'source' : 'IPython.kernel.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
326 'source' : 'IPython.kernel.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
327 'filename' : filename,
327 'filename' : filename,
328 'line_number' : lineno
328 'line_number' : lineno
329 }
329 }
330 self.shell.payload_manager.write_payload(payload)
330 self.shell.payload_manager.write_payload(payload)
331
331
332 # A few magics that are adapted to the specifics of using pexpect and a
332 # A few magics that are adapted to the specifics of using pexpect and a
333 # remote terminal
333 # remote terminal
334
334
335 @line_magic
335 @line_magic
336 def clear(self, arg_s):
336 def clear(self, arg_s):
337 """Clear the terminal."""
337 """Clear the terminal."""
338 if os.name == 'posix':
338 if os.name == 'posix':
339 self.shell.system("clear")
339 self.shell.system("clear")
340 else:
340 else:
341 self.shell.system("cls")
341 self.shell.system("cls")
342
342
343 if os.name == 'nt':
343 if os.name == 'nt':
344 # This is the usual name in windows
344 # This is the usual name in windows
345 cls = line_magic('cls')(clear)
345 cls = line_magic('cls')(clear)
346
346
347 # Terminal pagers won't work over pexpect, but we do have our own pager
347 # Terminal pagers won't work over pexpect, but we do have our own pager
348
348
349 @line_magic
349 @line_magic
350 def less(self, arg_s):
350 def less(self, arg_s):
351 """Show a file through the pager.
351 """Show a file through the pager.
352
352
353 Files ending in .py are syntax-highlighted."""
353 Files ending in .py are syntax-highlighted."""
354 if not arg_s:
354 if not arg_s:
355 raise UsageError('Missing filename.')
355 raise UsageError('Missing filename.')
356
356
357 cont = open(arg_s).read()
357 cont = open(arg_s).read()
358 if arg_s.endswith('.py'):
358 if arg_s.endswith('.py'):
359 cont = self.shell.pycolorize(openpy.read_py_file(arg_s, skip_encoding_cookie=False))
359 cont = self.shell.pycolorize(openpy.read_py_file(arg_s, skip_encoding_cookie=False))
360 else:
360 else:
361 cont = open(arg_s).read()
361 cont = open(arg_s).read()
362 page.page(cont)
362 page.page(cont)
363
363
364 more = line_magic('more')(less)
364 more = line_magic('more')(less)
365
365
366 # Man calls a pager, so we also need to redefine it
366 # Man calls a pager, so we also need to redefine it
367 if os.name == 'posix':
367 if os.name == 'posix':
368 @line_magic
368 @line_magic
369 def man(self, arg_s):
369 def man(self, arg_s):
370 """Find the man page for the given command and display in pager."""
370 """Find the man page for the given command and display in pager."""
371 page.page(self.shell.getoutput('man %s | col -b' % arg_s,
371 page.page(self.shell.getoutput('man %s | col -b' % arg_s,
372 split=False))
372 split=False))
373
373
374 @line_magic
374 @line_magic
375 def connect_info(self, arg_s):
375 def connect_info(self, arg_s):
376 """Print information for connecting other clients to this kernel
376 """Print information for connecting other clients to this kernel
377
377
378 It will print the contents of this session's connection file, as well as
378 It will print the contents of this session's connection file, as well as
379 shortcuts for local clients.
379 shortcuts for local clients.
380
380
381 In the simplest case, when called from the most recently launched kernel,
381 In the simplest case, when called from the most recently launched kernel,
382 secondary clients can be connected, simply with:
382 secondary clients can be connected, simply with:
383
383
384 $> ipython <app> --existing
384 $> ipython <app> --existing
385
385
386 """
386 """
387
387
388 from IPython.core.application import BaseIPythonApplication as BaseIPApp
388 from IPython.core.application import BaseIPythonApplication as BaseIPApp
389
389
390 if BaseIPApp.initialized():
390 if BaseIPApp.initialized():
391 app = BaseIPApp.instance()
391 app = BaseIPApp.instance()
392 security_dir = app.profile_dir.security_dir
392 security_dir = app.profile_dir.security_dir
393 profile = app.profile
393 profile = app.profile
394 else:
394 else:
395 profile = 'default'
395 profile = 'default'
396 security_dir = ''
396 security_dir = ''
397
397
398 try:
398 try:
399 connection_file = get_connection_file()
399 connection_file = get_connection_file()
400 info = get_connection_info(unpack=False)
400 info = get_connection_info(unpack=False)
401 except Exception as e:
401 except Exception as e:
402 error("Could not get connection info: %r" % e)
402 error("Could not get connection info: %r" % e)
403 return
403 return
404
404
405 # add profile flag for non-default profile
405 # add profile flag for non-default profile
406 profile_flag = "--profile %s" % profile if profile != 'default' else ""
406 profile_flag = "--profile %s" % profile if profile != 'default' else ""
407
407
408 # if it's in the security dir, truncate to basename
408 # if it's in the security dir, truncate to basename
409 if security_dir == os.path.dirname(connection_file):
409 if security_dir == os.path.dirname(connection_file):
410 connection_file = os.path.basename(connection_file)
410 connection_file = os.path.basename(connection_file)
411
411
412
412
413 print (info + '\n')
413 print (info + '\n')
414 print ("Paste the above JSON into a file, and connect with:\n"
414 print ("Paste the above JSON into a file, and connect with:\n"
415 " $> ipython <app> --existing <file>\n"
415 " $> ipython <app> --existing <file>\n"
416 "or, if you are local, you can connect with just:\n"
416 "or, if you are local, you can connect with just:\n"
417 " $> ipython <app> --existing {0} {1}\n"
417 " $> ipython <app> --existing {0} {1}\n"
418 "or even just:\n"
418 "or even just:\n"
419 " $> ipython <app> --existing {1}\n"
419 " $> ipython <app> --existing {1}\n"
420 "if this is the most recent IPython session you have started.".format(
420 "if this is the most recent IPython session you have started.".format(
421 connection_file, profile_flag
421 connection_file, profile_flag
422 )
422 )
423 )
423 )
424
424
425 @line_magic
425 @line_magic
426 def qtconsole(self, arg_s):
426 def qtconsole(self, arg_s):
427 """Open a qtconsole connected to this kernel.
427 """Open a qtconsole connected to this kernel.
428
428
429 Useful for connecting a qtconsole to running notebooks, for better
429 Useful for connecting a qtconsole to running notebooks, for better
430 debugging.
430 debugging.
431 """
431 """
432
432
433 # %qtconsole should imply bind_kernel for engines:
433 # %qtconsole should imply bind_kernel for engines:
434 try:
434 try:
435 from IPython.parallel import bind_kernel
435 from IPython.parallel import bind_kernel
436 except ImportError:
436 except ImportError:
437 # technically possible, because parallel has higher pyzmq min-version
437 # technically possible, because parallel has higher pyzmq min-version
438 pass
438 pass
439 else:
439 else:
440 bind_kernel()
440 bind_kernel()
441
441
442 try:
442 try:
443 p = connect_qtconsole(argv=arg_split(arg_s, os.name=='posix'))
443 p = connect_qtconsole(argv=arg_split(arg_s, os.name=='posix'))
444 except Exception as e:
444 except Exception as e:
445 error("Could not start qtconsole: %r" % e)
445 error("Could not start qtconsole: %r" % e)
446 return
446 return
447
447
448 def safe_unicode(e):
448 def safe_unicode(e):
449 """unicode(e) with various fallbacks. Used for exceptions, which may not be
449 """unicode(e) with various fallbacks. Used for exceptions, which may not be
450 safe to call unicode() on.
450 safe to call unicode() on.
451 """
451 """
452 try:
452 try:
453 return unicode(e)
453 return unicode(e)
454 except UnicodeError:
454 except UnicodeError:
455 pass
455 pass
456
456
457 try:
457 try:
458 return py3compat.str_to_unicode(str(e))
458 return py3compat.str_to_unicode(str(e))
459 except UnicodeError:
459 except UnicodeError:
460 pass
460 pass
461
461
462 try:
462 try:
463 return py3compat.str_to_unicode(repr(e))
463 return py3compat.str_to_unicode(repr(e))
464 except UnicodeError:
464 except UnicodeError:
465 pass
465 pass
466
466
467 return u'Unrecoverably corrupt evalue'
467 return u'Unrecoverably corrupt evalue'
468
468
469
469
470 class ZMQInteractiveShell(InteractiveShell):
470 class ZMQInteractiveShell(InteractiveShell):
471 """A subclass of InteractiveShell for ZMQ."""
471 """A subclass of InteractiveShell for ZMQ."""
472
472
473 displayhook_class = Type(ZMQShellDisplayHook)
473 displayhook_class = Type(ZMQShellDisplayHook)
474 display_pub_class = Type(ZMQDisplayPublisher)
474 display_pub_class = Type(ZMQDisplayPublisher)
475 data_pub_class = Type(ZMQDataPublisher)
475 data_pub_class = Type(ZMQDataPublisher)
476
476
477 # Override the traitlet in the parent class, because there's no point using
477 # Override the traitlet in the parent class, because there's no point using
478 # readline for the kernel. Can be removed when the readline code is moved
478 # readline for the kernel. Can be removed when the readline code is moved
479 # to the terminal frontend.
479 # to the terminal frontend.
480 colors_force = CBool(True)
480 colors_force = CBool(True)
481 readline_use = CBool(False)
481 readline_use = CBool(False)
482 # autoindent has no meaning in a zmqshell, and attempting to enable it
482 # autoindent has no meaning in a zmqshell, and attempting to enable it
483 # will print a warning in the absence of readline.
483 # will print a warning in the absence of readline.
484 autoindent = CBool(False)
484 autoindent = CBool(False)
485
485
486 exiter = Instance(ZMQExitAutocall)
486 exiter = Instance(ZMQExitAutocall)
487 def _exiter_default(self):
487 def _exiter_default(self):
488 return ZMQExitAutocall(self)
488 return ZMQExitAutocall(self)
489
489
490 def _exit_now_changed(self, name, old, new):
490 def _exit_now_changed(self, name, old, new):
491 """stop eventloop when exit_now fires"""
491 """stop eventloop when exit_now fires"""
492 if new:
492 if new:
493 loop = ioloop.IOLoop.instance()
493 loop = ioloop.IOLoop.instance()
494 loop.add_timeout(time.time()+0.1, loop.stop)
494 loop.add_timeout(time.time()+0.1, loop.stop)
495
495
496 keepkernel_on_exit = None
496 keepkernel_on_exit = None
497
497
498 # Over ZeroMQ, GUI control isn't done with PyOS_InputHook as there is no
498 # Over ZeroMQ, GUI control isn't done with PyOS_InputHook as there is no
499 # interactive input being read; we provide event loop support in ipkernel
499 # interactive input being read; we provide event loop support in ipkernel
500 from .eventloops import enable_gui
500 from .eventloops import enable_gui
501 enable_gui = staticmethod(enable_gui)
501 enable_gui = staticmethod(enable_gui)
502
502
503 def init_environment(self):
503 def init_environment(self):
504 """Configure the user's environment.
504 """Configure the user's environment.
505
505
506 """
506 """
507 env = os.environ
507 env = os.environ
508 # These two ensure 'ls' produces nice coloring on BSD-derived systems
508 # These two ensure 'ls' produces nice coloring on BSD-derived systems
509 env['TERM'] = 'xterm-color'
509 env['TERM'] = 'xterm-color'
510 env['CLICOLOR'] = '1'
510 env['CLICOLOR'] = '1'
511 # Since normal pagers don't work at all (over pexpect we don't have
511 # Since normal pagers don't work at all (over pexpect we don't have
512 # single-key control of the subprocess), try to disable paging in
512 # single-key control of the subprocess), try to disable paging in
513 # subprocesses as much as possible.
513 # subprocesses as much as possible.
514 env['PAGER'] = 'cat'
514 env['PAGER'] = 'cat'
515 env['GIT_PAGER'] = 'cat'
515 env['GIT_PAGER'] = 'cat'
516
516
517 # And install the payload version of page.
517 # And install the payload version of page.
518 install_payload_page()
518 install_payload_page()
519
519
520 def auto_rewrite_input(self, cmd):
520 def auto_rewrite_input(self, cmd):
521 """Called to show the auto-rewritten input for autocall and friends.
521 """Called to show the auto-rewritten input for autocall and friends.
522
522
523 FIXME: this payload is currently not correctly processed by the
523 FIXME: this payload is currently not correctly processed by the
524 frontend.
524 frontend.
525 """
525 """
526 new = self.prompt_manager.render('rewrite') + cmd
526 new = self.prompt_manager.render('rewrite') + cmd
527 payload = dict(
527 payload = dict(
528 source='IPython.kernel.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input',
528 source='IPython.kernel.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input',
529 transformed_input=new,
529 transformed_input=new,
530 )
530 )
531 self.payload_manager.write_payload(payload)
531 self.payload_manager.write_payload(payload)
532
532
533 def ask_exit(self):
533 def ask_exit(self):
534 """Engage the exit actions."""
534 """Engage the exit actions."""
535 self.exit_now = True
535 self.exit_now = True
536 payload = dict(
536 payload = dict(
537 source='IPython.kernel.zmq.zmqshell.ZMQInteractiveShell.ask_exit',
537 source='IPython.kernel.zmq.zmqshell.ZMQInteractiveShell.ask_exit',
538 exit=True,
538 exit=True,
539 keepkernel=self.keepkernel_on_exit,
539 keepkernel=self.keepkernel_on_exit,
540 )
540 )
541 self.payload_manager.write_payload(payload)
541 self.payload_manager.write_payload(payload)
542
542
543 def _showtraceback(self, etype, evalue, stb):
543 def _showtraceback(self, etype, evalue, stb):
544
544
545 exc_content = {
545 exc_content = {
546 u'traceback' : stb,
546 u'traceback' : stb,
547 u'ename' : unicode(etype.__name__),
547 u'ename' : unicode(etype.__name__),
548 u'evalue' : safe_unicode(evalue)
548 u'evalue' : safe_unicode(evalue)
549 }
549 }
550
550
551 dh = self.displayhook
551 dh = self.displayhook
552 # Send exception info over pub socket for other clients than the caller
552 # Send exception info over pub socket for other clients than the caller
553 # to pick up
553 # to pick up
554 topic = None
554 topic = None
555 if dh.topic:
555 if dh.topic:
556 topic = dh.topic.replace(b'pyout', b'pyerr')
556 topic = dh.topic.replace(b'pyout', b'pyerr')
557
557
558 exc_msg = dh.session.send(dh.pub_socket, u'pyerr', json_clean(exc_content), dh.parent_header, ident=topic)
558 exc_msg = dh.session.send(dh.pub_socket, u'pyerr', json_clean(exc_content), dh.parent_header, ident=topic)
559
559
560 # FIXME - Hack: store exception info in shell object. Right now, the
560 # FIXME - Hack: store exception info in shell object. Right now, the
561 # caller is reading this info after the fact, we need to fix this logic
561 # caller is reading this info after the fact, we need to fix this logic
562 # to remove this hack. Even uglier, we need to store the error status
562 # to remove this hack. Even uglier, we need to store the error status
563 # here, because in the main loop, the logic that sets it is being
563 # here, because in the main loop, the logic that sets it is being
564 # skipped because runlines swallows the exceptions.
564 # skipped because runlines swallows the exceptions.
565 exc_content[u'status'] = u'error'
565 exc_content[u'status'] = u'error'
566 self._reply_content = exc_content
566 self._reply_content = exc_content
567 # /FIXME
567 # /FIXME
568
568
569 return exc_content
569 return exc_content
570
570
571 def set_next_input(self, text):
571 def set_next_input(self, text):
572 """Send the specified text to the frontend to be presented at the next
572 """Send the specified text to the frontend to be presented at the next
573 input cell."""
573 input cell."""
574 payload = dict(
574 payload = dict(
575 source='IPython.kernel.zmq.zmqshell.ZMQInteractiveShell.set_next_input',
575 source='IPython.kernel.zmq.zmqshell.ZMQInteractiveShell.set_next_input',
576 text=text
576 text=text
577 )
577 )
578 self.payload_manager.write_payload(payload)
578 self.payload_manager.write_payload(payload)
579
579
580 #-------------------------------------------------------------------------
580 #-------------------------------------------------------------------------
581 # Things related to magics
581 # Things related to magics
582 #-------------------------------------------------------------------------
582 #-------------------------------------------------------------------------
583
583
584 def init_magics(self):
584 def init_magics(self):
585 super(ZMQInteractiveShell, self).init_magics()
585 super(ZMQInteractiveShell, self).init_magics()
586 self.register_magics(KernelMagics)
586 self.register_magics(KernelMagics)
587 self.magics_manager.register_alias('ed', 'edit')
587 self.magics_manager.register_alias('ed', 'edit')
588
588
589
589
590
590
591 InteractiveShellABC.register(ZMQInteractiveShell)
591 InteractiveShellABC.register(ZMQInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now