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