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