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