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