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