##// END OF EJS Templates
Missed a few uses of prompt manager in doctest code
Thomas Kluyver -
Show More
@@ -1,597 +1,595 b''
1 """Implementation of basic magic functions."""
1 """Implementation of basic magic functions."""
2
2
3 from __future__ import print_function
3 from __future__ import print_function
4 from __future__ import absolute_import
4 from __future__ import absolute_import
5
5
6 import io
6 import io
7 import sys
7 import sys
8 from pprint import pformat
8 from pprint import pformat
9
9
10 from IPython.core import magic_arguments, page
10 from IPython.core import magic_arguments, page
11 from IPython.core.error import UsageError
11 from IPython.core.error import UsageError
12 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
12 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
13 from IPython.utils.text import format_screen, dedent, indent
13 from IPython.utils.text import format_screen, dedent, indent
14 from IPython.testing.skipdoctest import skip_doctest
14 from IPython.testing.skipdoctest import skip_doctest
15 from IPython.utils.ipstruct import Struct
15 from IPython.utils.ipstruct import Struct
16 from IPython.utils.path import unquote_filename
16 from IPython.utils.path import unquote_filename
17 from IPython.utils.py3compat import unicode_type
17 from IPython.utils.py3compat import unicode_type
18 from warnings import warn
18 from warnings import warn
19 from logging import error
19 from logging import error
20
20
21
21
22 class MagicsDisplay(object):
22 class MagicsDisplay(object):
23 def __init__(self, magics_manager):
23 def __init__(self, magics_manager):
24 self.magics_manager = magics_manager
24 self.magics_manager = magics_manager
25
25
26 def _lsmagic(self):
26 def _lsmagic(self):
27 """The main implementation of the %lsmagic"""
27 """The main implementation of the %lsmagic"""
28 mesc = magic_escapes['line']
28 mesc = magic_escapes['line']
29 cesc = magic_escapes['cell']
29 cesc = magic_escapes['cell']
30 mman = self.magics_manager
30 mman = self.magics_manager
31 magics = mman.lsmagic()
31 magics = mman.lsmagic()
32 out = ['Available line magics:',
32 out = ['Available line magics:',
33 mesc + (' '+mesc).join(sorted(magics['line'])),
33 mesc + (' '+mesc).join(sorted(magics['line'])),
34 '',
34 '',
35 'Available cell magics:',
35 'Available cell magics:',
36 cesc + (' '+cesc).join(sorted(magics['cell'])),
36 cesc + (' '+cesc).join(sorted(magics['cell'])),
37 '',
37 '',
38 mman.auto_status()]
38 mman.auto_status()]
39 return '\n'.join(out)
39 return '\n'.join(out)
40
40
41 def _repr_pretty_(self, p, cycle):
41 def _repr_pretty_(self, p, cycle):
42 p.text(self._lsmagic())
42 p.text(self._lsmagic())
43
43
44 def __str__(self):
44 def __str__(self):
45 return self._lsmagic()
45 return self._lsmagic()
46
46
47 def _jsonable(self):
47 def _jsonable(self):
48 """turn magics dict into jsonable dict of the same structure
48 """turn magics dict into jsonable dict of the same structure
49
49
50 replaces object instances with their class names as strings
50 replaces object instances with their class names as strings
51 """
51 """
52 magic_dict = {}
52 magic_dict = {}
53 mman = self.magics_manager
53 mman = self.magics_manager
54 magics = mman.lsmagic()
54 magics = mman.lsmagic()
55 for key, subdict in magics.items():
55 for key, subdict in magics.items():
56 d = {}
56 d = {}
57 magic_dict[key] = d
57 magic_dict[key] = d
58 for name, obj in subdict.items():
58 for name, obj in subdict.items():
59 try:
59 try:
60 classname = obj.__self__.__class__.__name__
60 classname = obj.__self__.__class__.__name__
61 except AttributeError:
61 except AttributeError:
62 classname = 'Other'
62 classname = 'Other'
63
63
64 d[name] = classname
64 d[name] = classname
65 return magic_dict
65 return magic_dict
66
66
67 def _repr_json_(self):
67 def _repr_json_(self):
68 return self._jsonable()
68 return self._jsonable()
69
69
70
70
71 @magics_class
71 @magics_class
72 class BasicMagics(Magics):
72 class BasicMagics(Magics):
73 """Magics that provide central IPython functionality.
73 """Magics that provide central IPython functionality.
74
74
75 These are various magics that don't fit into specific categories but that
75 These are various magics that don't fit into specific categories but that
76 are all part of the base 'IPython experience'."""
76 are all part of the base 'IPython experience'."""
77
77
78 @magic_arguments.magic_arguments()
78 @magic_arguments.magic_arguments()
79 @magic_arguments.argument(
79 @magic_arguments.argument(
80 '-l', '--line', action='store_true',
80 '-l', '--line', action='store_true',
81 help="""Create a line magic alias."""
81 help="""Create a line magic alias."""
82 )
82 )
83 @magic_arguments.argument(
83 @magic_arguments.argument(
84 '-c', '--cell', action='store_true',
84 '-c', '--cell', action='store_true',
85 help="""Create a cell magic alias."""
85 help="""Create a cell magic alias."""
86 )
86 )
87 @magic_arguments.argument(
87 @magic_arguments.argument(
88 'name',
88 'name',
89 help="""Name of the magic to be created."""
89 help="""Name of the magic to be created."""
90 )
90 )
91 @magic_arguments.argument(
91 @magic_arguments.argument(
92 'target',
92 'target',
93 help="""Name of the existing line or cell magic."""
93 help="""Name of the existing line or cell magic."""
94 )
94 )
95 @line_magic
95 @line_magic
96 def alias_magic(self, line=''):
96 def alias_magic(self, line=''):
97 """Create an alias for an existing line or cell magic.
97 """Create an alias for an existing line or cell magic.
98
98
99 Examples
99 Examples
100 --------
100 --------
101 ::
101 ::
102
102
103 In [1]: %alias_magic t timeit
103 In [1]: %alias_magic t timeit
104 Created `%t` as an alias for `%timeit`.
104 Created `%t` as an alias for `%timeit`.
105 Created `%%t` as an alias for `%%timeit`.
105 Created `%%t` as an alias for `%%timeit`.
106
106
107 In [2]: %t -n1 pass
107 In [2]: %t -n1 pass
108 1 loops, best of 3: 954 ns per loop
108 1 loops, best of 3: 954 ns per loop
109
109
110 In [3]: %%t -n1
110 In [3]: %%t -n1
111 ...: pass
111 ...: pass
112 ...:
112 ...:
113 1 loops, best of 3: 954 ns per loop
113 1 loops, best of 3: 954 ns per loop
114
114
115 In [4]: %alias_magic --cell whereami pwd
115 In [4]: %alias_magic --cell whereami pwd
116 UsageError: Cell magic function `%%pwd` not found.
116 UsageError: Cell magic function `%%pwd` not found.
117 In [5]: %alias_magic --line whereami pwd
117 In [5]: %alias_magic --line whereami pwd
118 Created `%whereami` as an alias for `%pwd`.
118 Created `%whereami` as an alias for `%pwd`.
119
119
120 In [6]: %whereami
120 In [6]: %whereami
121 Out[6]: u'/home/testuser'
121 Out[6]: u'/home/testuser'
122 """
122 """
123 args = magic_arguments.parse_argstring(self.alias_magic, line)
123 args = magic_arguments.parse_argstring(self.alias_magic, line)
124 shell = self.shell
124 shell = self.shell
125 mman = self.shell.magics_manager
125 mman = self.shell.magics_manager
126 escs = ''.join(magic_escapes.values())
126 escs = ''.join(magic_escapes.values())
127
127
128 target = args.target.lstrip(escs)
128 target = args.target.lstrip(escs)
129 name = args.name.lstrip(escs)
129 name = args.name.lstrip(escs)
130
130
131 # Find the requested magics.
131 # Find the requested magics.
132 m_line = shell.find_magic(target, 'line')
132 m_line = shell.find_magic(target, 'line')
133 m_cell = shell.find_magic(target, 'cell')
133 m_cell = shell.find_magic(target, 'cell')
134 if args.line and m_line is None:
134 if args.line and m_line is None:
135 raise UsageError('Line magic function `%s%s` not found.' %
135 raise UsageError('Line magic function `%s%s` not found.' %
136 (magic_escapes['line'], target))
136 (magic_escapes['line'], target))
137 if args.cell and m_cell is None:
137 if args.cell and m_cell is None:
138 raise UsageError('Cell magic function `%s%s` not found.' %
138 raise UsageError('Cell magic function `%s%s` not found.' %
139 (magic_escapes['cell'], target))
139 (magic_escapes['cell'], target))
140
140
141 # If --line and --cell are not specified, default to the ones
141 # If --line and --cell are not specified, default to the ones
142 # that are available.
142 # that are available.
143 if not args.line and not args.cell:
143 if not args.line and not args.cell:
144 if not m_line and not m_cell:
144 if not m_line and not m_cell:
145 raise UsageError(
145 raise UsageError(
146 'No line or cell magic with name `%s` found.' % target
146 'No line or cell magic with name `%s` found.' % target
147 )
147 )
148 args.line = bool(m_line)
148 args.line = bool(m_line)
149 args.cell = bool(m_cell)
149 args.cell = bool(m_cell)
150
150
151 if args.line:
151 if args.line:
152 mman.register_alias(name, target, 'line')
152 mman.register_alias(name, target, 'line')
153 print('Created `%s%s` as an alias for `%s%s`.' % (
153 print('Created `%s%s` as an alias for `%s%s`.' % (
154 magic_escapes['line'], name,
154 magic_escapes['line'], name,
155 magic_escapes['line'], target))
155 magic_escapes['line'], target))
156
156
157 if args.cell:
157 if args.cell:
158 mman.register_alias(name, target, 'cell')
158 mman.register_alias(name, target, 'cell')
159 print('Created `%s%s` as an alias for `%s%s`.' % (
159 print('Created `%s%s` as an alias for `%s%s`.' % (
160 magic_escapes['cell'], name,
160 magic_escapes['cell'], name,
161 magic_escapes['cell'], target))
161 magic_escapes['cell'], target))
162
162
163 @line_magic
163 @line_magic
164 def lsmagic(self, parameter_s=''):
164 def lsmagic(self, parameter_s=''):
165 """List currently available magic functions."""
165 """List currently available magic functions."""
166 return MagicsDisplay(self.shell.magics_manager)
166 return MagicsDisplay(self.shell.magics_manager)
167
167
168 def _magic_docs(self, brief=False, rest=False):
168 def _magic_docs(self, brief=False, rest=False):
169 """Return docstrings from magic functions."""
169 """Return docstrings from magic functions."""
170 mman = self.shell.magics_manager
170 mman = self.shell.magics_manager
171 docs = mman.lsmagic_docs(brief, missing='No documentation')
171 docs = mman.lsmagic_docs(brief, missing='No documentation')
172
172
173 if rest:
173 if rest:
174 format_string = '**%s%s**::\n\n%s\n\n'
174 format_string = '**%s%s**::\n\n%s\n\n'
175 else:
175 else:
176 format_string = '%s%s:\n%s\n'
176 format_string = '%s%s:\n%s\n'
177
177
178 return ''.join(
178 return ''.join(
179 [format_string % (magic_escapes['line'], fname,
179 [format_string % (magic_escapes['line'], fname,
180 indent(dedent(fndoc)))
180 indent(dedent(fndoc)))
181 for fname, fndoc in sorted(docs['line'].items())]
181 for fname, fndoc in sorted(docs['line'].items())]
182 +
182 +
183 [format_string % (magic_escapes['cell'], fname,
183 [format_string % (magic_escapes['cell'], fname,
184 indent(dedent(fndoc)))
184 indent(dedent(fndoc)))
185 for fname, fndoc in sorted(docs['cell'].items())]
185 for fname, fndoc in sorted(docs['cell'].items())]
186 )
186 )
187
187
188 @line_magic
188 @line_magic
189 def magic(self, parameter_s=''):
189 def magic(self, parameter_s=''):
190 """Print information about the magic function system.
190 """Print information about the magic function system.
191
191
192 Supported formats: -latex, -brief, -rest
192 Supported formats: -latex, -brief, -rest
193 """
193 """
194
194
195 mode = ''
195 mode = ''
196 try:
196 try:
197 mode = parameter_s.split()[0][1:]
197 mode = parameter_s.split()[0][1:]
198 except IndexError:
198 except IndexError:
199 pass
199 pass
200
200
201 brief = (mode == 'brief')
201 brief = (mode == 'brief')
202 rest = (mode == 'rest')
202 rest = (mode == 'rest')
203 magic_docs = self._magic_docs(brief, rest)
203 magic_docs = self._magic_docs(brief, rest)
204
204
205 if mode == 'latex':
205 if mode == 'latex':
206 print(self.format_latex(magic_docs))
206 print(self.format_latex(magic_docs))
207 return
207 return
208 else:
208 else:
209 magic_docs = format_screen(magic_docs)
209 magic_docs = format_screen(magic_docs)
210
210
211 out = ["""
211 out = ["""
212 IPython's 'magic' functions
212 IPython's 'magic' functions
213 ===========================
213 ===========================
214
214
215 The magic function system provides a series of functions which allow you to
215 The magic function system provides a series of functions which allow you to
216 control the behavior of IPython itself, plus a lot of system-type
216 control the behavior of IPython itself, plus a lot of system-type
217 features. There are two kinds of magics, line-oriented and cell-oriented.
217 features. There are two kinds of magics, line-oriented and cell-oriented.
218
218
219 Line magics are prefixed with the % character and work much like OS
219 Line magics are prefixed with the % character and work much like OS
220 command-line calls: they get as an argument the rest of the line, where
220 command-line calls: they get as an argument the rest of the line, where
221 arguments are passed without parentheses or quotes. For example, this will
221 arguments are passed without parentheses or quotes. For example, this will
222 time the given statement::
222 time the given statement::
223
223
224 %timeit range(1000)
224 %timeit range(1000)
225
225
226 Cell magics are prefixed with a double %%, and they are functions that get as
226 Cell magics are prefixed with a double %%, and they are functions that get as
227 an argument not only the rest of the line, but also the lines below it in a
227 an argument not only the rest of the line, but also the lines below it in a
228 separate argument. These magics are called with two arguments: the rest of the
228 separate argument. These magics are called with two arguments: the rest of the
229 call line and the body of the cell, consisting of the lines below the first.
229 call line and the body of the cell, consisting of the lines below the first.
230 For example::
230 For example::
231
231
232 %%timeit x = numpy.random.randn((100, 100))
232 %%timeit x = numpy.random.randn((100, 100))
233 numpy.linalg.svd(x)
233 numpy.linalg.svd(x)
234
234
235 will time the execution of the numpy svd routine, running the assignment of x
235 will time the execution of the numpy svd routine, running the assignment of x
236 as part of the setup phase, which is not timed.
236 as part of the setup phase, which is not timed.
237
237
238 In a line-oriented client (the terminal or Qt console IPython), starting a new
238 In a line-oriented client (the terminal or Qt console IPython), starting a new
239 input with %% will automatically enter cell mode, and IPython will continue
239 input with %% will automatically enter cell mode, and IPython will continue
240 reading input until a blank line is given. In the notebook, simply type the
240 reading input until a blank line is given. In the notebook, simply type the
241 whole cell as one entity, but keep in mind that the %% escape can only be at
241 whole cell as one entity, but keep in mind that the %% escape can only be at
242 the very start of the cell.
242 the very start of the cell.
243
243
244 NOTE: If you have 'automagic' enabled (via the command line option or with the
244 NOTE: If you have 'automagic' enabled (via the command line option or with the
245 %automagic function), you don't need to type in the % explicitly for line
245 %automagic function), you don't need to type in the % explicitly for line
246 magics; cell magics always require an explicit '%%' escape. By default,
246 magics; cell magics always require an explicit '%%' escape. By default,
247 IPython ships with automagic on, so you should only rarely need the % escape.
247 IPython ships with automagic on, so you should only rarely need the % escape.
248
248
249 Example: typing '%cd mydir' (without the quotes) changes your working directory
249 Example: typing '%cd mydir' (without the quotes) changes your working directory
250 to 'mydir', if it exists.
250 to 'mydir', if it exists.
251
251
252 For a list of the available magic functions, use %lsmagic. For a description
252 For a list of the available magic functions, use %lsmagic. For a description
253 of any of them, type %magic_name?, e.g. '%cd?'.
253 of any of them, type %magic_name?, e.g. '%cd?'.
254
254
255 Currently the magic system has the following functions:""",
255 Currently the magic system has the following functions:""",
256 magic_docs,
256 magic_docs,
257 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
257 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
258 str(self.lsmagic()),
258 str(self.lsmagic()),
259 ]
259 ]
260 page.page('\n'.join(out))
260 page.page('\n'.join(out))
261
261
262
262
263 @line_magic
263 @line_magic
264 def page(self, parameter_s=''):
264 def page(self, parameter_s=''):
265 """Pretty print the object and display it through a pager.
265 """Pretty print the object and display it through a pager.
266
266
267 %page [options] OBJECT
267 %page [options] OBJECT
268
268
269 If no object is given, use _ (last output).
269 If no object is given, use _ (last output).
270
270
271 Options:
271 Options:
272
272
273 -r: page str(object), don't pretty-print it."""
273 -r: page str(object), don't pretty-print it."""
274
274
275 # After a function contributed by Olivier Aubert, slightly modified.
275 # After a function contributed by Olivier Aubert, slightly modified.
276
276
277 # Process options/args
277 # Process options/args
278 opts, args = self.parse_options(parameter_s, 'r')
278 opts, args = self.parse_options(parameter_s, 'r')
279 raw = 'r' in opts
279 raw = 'r' in opts
280
280
281 oname = args and args or '_'
281 oname = args and args or '_'
282 info = self.shell._ofind(oname)
282 info = self.shell._ofind(oname)
283 if info['found']:
283 if info['found']:
284 txt = (raw and str or pformat)( info['obj'] )
284 txt = (raw and str or pformat)( info['obj'] )
285 page.page(txt)
285 page.page(txt)
286 else:
286 else:
287 print('Object `%s` not found' % oname)
287 print('Object `%s` not found' % oname)
288
288
289 @line_magic
289 @line_magic
290 def profile(self, parameter_s=''):
290 def profile(self, parameter_s=''):
291 """Print your currently active IPython profile.
291 """Print your currently active IPython profile.
292
292
293 See Also
293 See Also
294 --------
294 --------
295 prun : run code using the Python profiler
295 prun : run code using the Python profiler
296 (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`)
296 (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`)
297 """
297 """
298 warn("%profile is now deprecated. Please use get_ipython().profile instead.")
298 warn("%profile is now deprecated. Please use get_ipython().profile instead.")
299 from IPython.core.application import BaseIPythonApplication
299 from IPython.core.application import BaseIPythonApplication
300 if BaseIPythonApplication.initialized():
300 if BaseIPythonApplication.initialized():
301 print(BaseIPythonApplication.instance().profile)
301 print(BaseIPythonApplication.instance().profile)
302 else:
302 else:
303 error("profile is an application-level value, but you don't appear to be in an IPython application")
303 error("profile is an application-level value, but you don't appear to be in an IPython application")
304
304
305 @line_magic
305 @line_magic
306 def pprint(self, parameter_s=''):
306 def pprint(self, parameter_s=''):
307 """Toggle pretty printing on/off."""
307 """Toggle pretty printing on/off."""
308 ptformatter = self.shell.display_formatter.formatters['text/plain']
308 ptformatter = self.shell.display_formatter.formatters['text/plain']
309 ptformatter.pprint = bool(1 - ptformatter.pprint)
309 ptformatter.pprint = bool(1 - ptformatter.pprint)
310 print('Pretty printing has been turned',
310 print('Pretty printing has been turned',
311 ['OFF','ON'][ptformatter.pprint])
311 ['OFF','ON'][ptformatter.pprint])
312
312
313 @line_magic
313 @line_magic
314 def colors(self, parameter_s=''):
314 def colors(self, parameter_s=''):
315 """Switch color scheme for prompts, info system and exception handlers.
315 """Switch color scheme for prompts, info system and exception handlers.
316
316
317 Currently implemented schemes: NoColor, Linux, LightBG.
317 Currently implemented schemes: NoColor, Linux, LightBG.
318
318
319 Color scheme names are not case-sensitive.
319 Color scheme names are not case-sensitive.
320
320
321 Examples
321 Examples
322 --------
322 --------
323 To get a plain black and white terminal::
323 To get a plain black and white terminal::
324
324
325 %colors nocolor
325 %colors nocolor
326 """
326 """
327 def color_switch_err(name):
327 def color_switch_err(name):
328 warn('Error changing %s color schemes.\n%s' %
328 warn('Error changing %s color schemes.\n%s' %
329 (name, sys.exc_info()[1]))
329 (name, sys.exc_info()[1]))
330
330
331
331
332 new_scheme = parameter_s.strip()
332 new_scheme = parameter_s.strip()
333 if not new_scheme:
333 if not new_scheme:
334 raise UsageError(
334 raise UsageError(
335 "%colors: you must specify a color scheme. See '%colors?'")
335 "%colors: you must specify a color scheme. See '%colors?'")
336 # local shortcut
336 # local shortcut
337 shell = self.shell
337 shell = self.shell
338
338
339
339
340
340
341 if not shell.colors_force:
341 if not shell.colors_force:
342 if sys.platform in {'win32', 'cli'}:
342 if sys.platform in {'win32', 'cli'}:
343 import IPython.utils.rlineimpl as readline
343 import IPython.utils.rlineimpl as readline
344 if not readline.have_readline:
344 if not readline.have_readline:
345 msg = """\
345 msg = """\
346 Proper color support under MS Windows requires the pyreadline library.
346 Proper color support under MS Windows requires the pyreadline library.
347 You can find it at:
347 You can find it at:
348 http://ipython.org/pyreadline.html
348 http://ipython.org/pyreadline.html
349
349
350 Defaulting color scheme to 'NoColor'"""
350 Defaulting color scheme to 'NoColor'"""
351 new_scheme = 'NoColor'
351 new_scheme = 'NoColor'
352 warn(msg)
352 warn(msg)
353
353
354 elif not shell.has_readline:
354 elif not shell.has_readline:
355 # Coloured prompts get messed up without readline
355 # Coloured prompts get messed up without readline
356 # Will remove this check after switching to prompt_toolkit
356 # Will remove this check after switching to prompt_toolkit
357 new_scheme = 'NoColor'
357 new_scheme = 'NoColor'
358
358
359 # Set exception colors
359 # Set exception colors
360 try:
360 try:
361 shell.InteractiveTB.set_colors(scheme = new_scheme)
361 shell.InteractiveTB.set_colors(scheme = new_scheme)
362 shell.SyntaxTB.set_colors(scheme = new_scheme)
362 shell.SyntaxTB.set_colors(scheme = new_scheme)
363 except:
363 except:
364 color_switch_err('exception')
364 color_switch_err('exception')
365
365
366 # Set info (for 'object?') colors
366 # Set info (for 'object?') colors
367 if shell.color_info:
367 if shell.color_info:
368 try:
368 try:
369 shell.inspector.set_active_scheme(new_scheme)
369 shell.inspector.set_active_scheme(new_scheme)
370 except:
370 except:
371 color_switch_err('object inspector')
371 color_switch_err('object inspector')
372 else:
372 else:
373 shell.inspector.set_active_scheme('NoColor')
373 shell.inspector.set_active_scheme('NoColor')
374
374
375 @line_magic
375 @line_magic
376 def xmode(self, parameter_s=''):
376 def xmode(self, parameter_s=''):
377 """Switch modes for the exception handlers.
377 """Switch modes for the exception handlers.
378
378
379 Valid modes: Plain, Context and Verbose.
379 Valid modes: Plain, Context and Verbose.
380
380
381 If called without arguments, acts as a toggle."""
381 If called without arguments, acts as a toggle."""
382
382
383 def xmode_switch_err(name):
383 def xmode_switch_err(name):
384 warn('Error changing %s exception modes.\n%s' %
384 warn('Error changing %s exception modes.\n%s' %
385 (name,sys.exc_info()[1]))
385 (name,sys.exc_info()[1]))
386
386
387 shell = self.shell
387 shell = self.shell
388 new_mode = parameter_s.strip().capitalize()
388 new_mode = parameter_s.strip().capitalize()
389 try:
389 try:
390 shell.InteractiveTB.set_mode(mode=new_mode)
390 shell.InteractiveTB.set_mode(mode=new_mode)
391 print('Exception reporting mode:',shell.InteractiveTB.mode)
391 print('Exception reporting mode:',shell.InteractiveTB.mode)
392 except:
392 except:
393 xmode_switch_err('user')
393 xmode_switch_err('user')
394
394
395 @line_magic
395 @line_magic
396 def quickref(self,arg):
396 def quickref(self,arg):
397 """ Show a quick reference sheet """
397 """ Show a quick reference sheet """
398 from IPython.core.usage import quick_reference
398 from IPython.core.usage import quick_reference
399 qr = quick_reference + self._magic_docs(brief=True)
399 qr = quick_reference + self._magic_docs(brief=True)
400 page.page(qr)
400 page.page(qr)
401
401
402 @line_magic
402 @line_magic
403 def doctest_mode(self, parameter_s=''):
403 def doctest_mode(self, parameter_s=''):
404 """Toggle doctest mode on and off.
404 """Toggle doctest mode on and off.
405
405
406 This mode is intended to make IPython behave as much as possible like a
406 This mode is intended to make IPython behave as much as possible like a
407 plain Python shell, from the perspective of how its prompts, exceptions
407 plain Python shell, from the perspective of how its prompts, exceptions
408 and output look. This makes it easy to copy and paste parts of a
408 and output look. This makes it easy to copy and paste parts of a
409 session into doctests. It does so by:
409 session into doctests. It does so by:
410
410
411 - Changing the prompts to the classic ``>>>`` ones.
411 - Changing the prompts to the classic ``>>>`` ones.
412 - Changing the exception reporting mode to 'Plain'.
412 - Changing the exception reporting mode to 'Plain'.
413 - Disabling pretty-printing of output.
413 - Disabling pretty-printing of output.
414
414
415 Note that IPython also supports the pasting of code snippets that have
415 Note that IPython also supports the pasting of code snippets that have
416 leading '>>>' and '...' prompts in them. This means that you can paste
416 leading '>>>' and '...' prompts in them. This means that you can paste
417 doctests from files or docstrings (even if they have leading
417 doctests from files or docstrings (even if they have leading
418 whitespace), and the code will execute correctly. You can then use
418 whitespace), and the code will execute correctly. You can then use
419 '%history -t' to see the translated history; this will give you the
419 '%history -t' to see the translated history; this will give you the
420 input after removal of all the leading prompts and whitespace, which
420 input after removal of all the leading prompts and whitespace, which
421 can be pasted back into an editor.
421 can be pasted back into an editor.
422
422
423 With these features, you can switch into this mode easily whenever you
423 With these features, you can switch into this mode easily whenever you
424 need to do testing and changes to doctests, without having to leave
424 need to do testing and changes to doctests, without having to leave
425 your existing IPython session.
425 your existing IPython session.
426 """
426 """
427
427
428 # Shorthands
428 # Shorthands
429 shell = self.shell
429 shell = self.shell
430 meta = shell.meta
430 meta = shell.meta
431 disp_formatter = self.shell.display_formatter
431 disp_formatter = self.shell.display_formatter
432 ptformatter = disp_formatter.formatters['text/plain']
432 ptformatter = disp_formatter.formatters['text/plain']
433 # dstore is a data store kept in the instance metadata bag to track any
433 # dstore is a data store kept in the instance metadata bag to track any
434 # changes we make, so we can undo them later.
434 # changes we make, so we can undo them later.
435 dstore = meta.setdefault('doctest_mode',Struct())
435 dstore = meta.setdefault('doctest_mode',Struct())
436 save_dstore = dstore.setdefault
436 save_dstore = dstore.setdefault
437
437
438 # save a few values we'll need to recover later
438 # save a few values we'll need to recover later
439 mode = save_dstore('mode',False)
439 mode = save_dstore('mode',False)
440 save_dstore('rc_pprint',ptformatter.pprint)
440 save_dstore('rc_pprint',ptformatter.pprint)
441 save_dstore('xmode',shell.InteractiveTB.mode)
441 save_dstore('xmode',shell.InteractiveTB.mode)
442 save_dstore('rc_separate_out',shell.separate_out)
442 save_dstore('rc_separate_out',shell.separate_out)
443 save_dstore('rc_separate_out2',shell.separate_out2)
443 save_dstore('rc_separate_out2',shell.separate_out2)
444 save_dstore('rc_prompts_pad_left',pm.justify)
445 save_dstore('rc_separate_in',shell.separate_in)
444 save_dstore('rc_separate_in',shell.separate_in)
446 save_dstore('rc_active_types',disp_formatter.active_types)
445 save_dstore('rc_active_types',disp_formatter.active_types)
447 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
448
446
449 if not mode:
447 if not mode:
450 # turn on
448 # turn on
451
449
452 # Prompt separators like plain python
450 # Prompt separators like plain python
453 shell.separate_in = ''
451 shell.separate_in = ''
454 shell.separate_out = ''
452 shell.separate_out = ''
455 shell.separate_out2 = ''
453 shell.separate_out2 = ''
456
454
457
455
458 ptformatter.pprint = False
456 ptformatter.pprint = False
459 disp_formatter.active_types = ['text/plain']
457 disp_formatter.active_types = ['text/plain']
460
458
461 shell.magic('xmode Plain')
459 shell.magic('xmode Plain')
462 else:
460 else:
463 # turn off
461 # turn off
464 shell.separate_in = dstore.rc_separate_in
462 shell.separate_in = dstore.rc_separate_in
465
463
466 shell.separate_out = dstore.rc_separate_out
464 shell.separate_out = dstore.rc_separate_out
467 shell.separate_out2 = dstore.rc_separate_out2
465 shell.separate_out2 = dstore.rc_separate_out2
468
466
469 ptformatter.pprint = dstore.rc_pprint
467 ptformatter.pprint = dstore.rc_pprint
470 disp_formatter.active_types = dstore.rc_active_types
468 disp_formatter.active_types = dstore.rc_active_types
471
469
472 shell.magic('xmode ' + dstore.xmode)
470 shell.magic('xmode ' + dstore.xmode)
473
471
474 # Store new mode and inform
472 # Store new mode and inform
475 dstore.mode = bool(1-int(mode))
473 dstore.mode = bool(1-int(mode))
476 mode_label = ['OFF','ON'][dstore.mode]
474 mode_label = ['OFF','ON'][dstore.mode]
477 print('Doctest mode is:', mode_label)
475 print('Doctest mode is:', mode_label)
478
476
479 @line_magic
477 @line_magic
480 def gui(self, parameter_s=''):
478 def gui(self, parameter_s=''):
481 """Enable or disable IPython GUI event loop integration.
479 """Enable or disable IPython GUI event loop integration.
482
480
483 %gui [GUINAME]
481 %gui [GUINAME]
484
482
485 This magic replaces IPython's threaded shells that were activated
483 This magic replaces IPython's threaded shells that were activated
486 using the (pylab/wthread/etc.) command line flags. GUI toolkits
484 using the (pylab/wthread/etc.) command line flags. GUI toolkits
487 can now be enabled at runtime and keyboard
485 can now be enabled at runtime and keyboard
488 interrupts should work without any problems. The following toolkits
486 interrupts should work without any problems. The following toolkits
489 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
487 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
490
488
491 %gui wx # enable wxPython event loop integration
489 %gui wx # enable wxPython event loop integration
492 %gui qt4|qt # enable PyQt4 event loop integration
490 %gui qt4|qt # enable PyQt4 event loop integration
493 %gui qt5 # enable PyQt5 event loop integration
491 %gui qt5 # enable PyQt5 event loop integration
494 %gui gtk # enable PyGTK event loop integration
492 %gui gtk # enable PyGTK event loop integration
495 %gui gtk3 # enable Gtk3 event loop integration
493 %gui gtk3 # enable Gtk3 event loop integration
496 %gui tk # enable Tk event loop integration
494 %gui tk # enable Tk event loop integration
497 %gui osx # enable Cocoa event loop integration
495 %gui osx # enable Cocoa event loop integration
498 # (requires %matplotlib 1.1)
496 # (requires %matplotlib 1.1)
499 %gui # disable all event loop integration
497 %gui # disable all event loop integration
500
498
501 WARNING: after any of these has been called you can simply create
499 WARNING: after any of these has been called you can simply create
502 an application object, but DO NOT start the event loop yourself, as
500 an application object, but DO NOT start the event loop yourself, as
503 we have already handled that.
501 we have already handled that.
504 """
502 """
505 opts, arg = self.parse_options(parameter_s, '')
503 opts, arg = self.parse_options(parameter_s, '')
506 if arg=='': arg = None
504 if arg=='': arg = None
507 try:
505 try:
508 return self.shell.enable_gui(arg)
506 return self.shell.enable_gui(arg)
509 except Exception as e:
507 except Exception as e:
510 # print simple error message, rather than traceback if we can't
508 # print simple error message, rather than traceback if we can't
511 # hook up the GUI
509 # hook up the GUI
512 error(str(e))
510 error(str(e))
513
511
514 @skip_doctest
512 @skip_doctest
515 @line_magic
513 @line_magic
516 def precision(self, s=''):
514 def precision(self, s=''):
517 """Set floating point precision for pretty printing.
515 """Set floating point precision for pretty printing.
518
516
519 Can set either integer precision or a format string.
517 Can set either integer precision or a format string.
520
518
521 If numpy has been imported and precision is an int,
519 If numpy has been imported and precision is an int,
522 numpy display precision will also be set, via ``numpy.set_printoptions``.
520 numpy display precision will also be set, via ``numpy.set_printoptions``.
523
521
524 If no argument is given, defaults will be restored.
522 If no argument is given, defaults will be restored.
525
523
526 Examples
524 Examples
527 --------
525 --------
528 ::
526 ::
529
527
530 In [1]: from math import pi
528 In [1]: from math import pi
531
529
532 In [2]: %precision 3
530 In [2]: %precision 3
533 Out[2]: u'%.3f'
531 Out[2]: u'%.3f'
534
532
535 In [3]: pi
533 In [3]: pi
536 Out[3]: 3.142
534 Out[3]: 3.142
537
535
538 In [4]: %precision %i
536 In [4]: %precision %i
539 Out[4]: u'%i'
537 Out[4]: u'%i'
540
538
541 In [5]: pi
539 In [5]: pi
542 Out[5]: 3
540 Out[5]: 3
543
541
544 In [6]: %precision %e
542 In [6]: %precision %e
545 Out[6]: u'%e'
543 Out[6]: u'%e'
546
544
547 In [7]: pi**10
545 In [7]: pi**10
548 Out[7]: 9.364805e+04
546 Out[7]: 9.364805e+04
549
547
550 In [8]: %precision
548 In [8]: %precision
551 Out[8]: u'%r'
549 Out[8]: u'%r'
552
550
553 In [9]: pi**10
551 In [9]: pi**10
554 Out[9]: 93648.047476082982
552 Out[9]: 93648.047476082982
555 """
553 """
556 ptformatter = self.shell.display_formatter.formatters['text/plain']
554 ptformatter = self.shell.display_formatter.formatters['text/plain']
557 ptformatter.float_precision = s
555 ptformatter.float_precision = s
558 return ptformatter.float_format
556 return ptformatter.float_format
559
557
560 @magic_arguments.magic_arguments()
558 @magic_arguments.magic_arguments()
561 @magic_arguments.argument(
559 @magic_arguments.argument(
562 '-e', '--export', action='store_true', default=False,
560 '-e', '--export', action='store_true', default=False,
563 help='Export IPython history as a notebook. The filename argument '
561 help='Export IPython history as a notebook. The filename argument '
564 'is used to specify the notebook name and format. For example '
562 'is used to specify the notebook name and format. For example '
565 'a filename of notebook.ipynb will result in a notebook name '
563 'a filename of notebook.ipynb will result in a notebook name '
566 'of "notebook" and a format of "json". Likewise using a ".py" '
564 'of "notebook" and a format of "json". Likewise using a ".py" '
567 'file extension will write the notebook as a Python script'
565 'file extension will write the notebook as a Python script'
568 )
566 )
569 @magic_arguments.argument(
567 @magic_arguments.argument(
570 'filename', type=unicode_type,
568 'filename', type=unicode_type,
571 help='Notebook name or filename'
569 help='Notebook name or filename'
572 )
570 )
573 @line_magic
571 @line_magic
574 def notebook(self, s):
572 def notebook(self, s):
575 """Export and convert IPython notebooks.
573 """Export and convert IPython notebooks.
576
574
577 This function can export the current IPython history to a notebook file.
575 This function can export the current IPython history to a notebook file.
578 For example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
576 For 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".
577 To export the history to "foo.py" do "%notebook -e foo.py".
580 """
578 """
581 args = magic_arguments.parse_argstring(self.notebook, s)
579 args = magic_arguments.parse_argstring(self.notebook, s)
582
580
583 from nbformat import write, v4
581 from nbformat import write, v4
584 args.filename = unquote_filename(args.filename)
582 args.filename = unquote_filename(args.filename)
585 if args.export:
583 if args.export:
586 cells = []
584 cells = []
587 hist = list(self.shell.history_manager.get_range())
585 hist = list(self.shell.history_manager.get_range())
588 if(len(hist)<=1):
586 if(len(hist)<=1):
589 raise ValueError('History is empty, cannot export')
587 raise ValueError('History is empty, cannot export')
590 for session, execution_count, source in hist[:-1]:
588 for session, execution_count, source in hist[:-1]:
591 cells.append(v4.new_code_cell(
589 cells.append(v4.new_code_cell(
592 execution_count=execution_count,
590 execution_count=execution_count,
593 source=source
591 source=source
594 ))
592 ))
595 nb = v4.new_notebook(cells=cells)
593 nb = v4.new_notebook(cells=cells)
596 with io.open(args.filename, 'w', encoding='utf-8') as f:
594 with io.open(args.filename, 'w', encoding='utf-8') as f:
597 write(nb, f, version=4)
595 write(nb, f, version=4)
General Comments 0
You need to be logged in to leave comments. Login now