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