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