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