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