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