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