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