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