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