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