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