##// END OF EJS Templates
reformat all of IPython.core
Matthias Bussonnier -
Show More
@@ -1,658 +1,657 b''
1 """Implementation of basic magic functions."""
1 """Implementation of basic magic functions."""
2
2
3
3
4 import argparse
4 import argparse
5 from logging import error
5 from logging import error
6 import io
6 import io
7 from pprint import pformat
7 from pprint import pformat
8 import sys
8 import sys
9 from warnings import warn
9 from warnings import warn
10
10
11 from traitlets.utils.importstring import import_item
11 from traitlets.utils.importstring import import_item
12 from IPython.core import magic_arguments, page
12 from IPython.core import magic_arguments, page
13 from IPython.core.error import UsageError
13 from IPython.core.error import UsageError
14 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
14 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
15 from IPython.utils.text import format_screen, dedent, indent
15 from IPython.utils.text import format_screen, dedent, indent
16 from IPython.testing.skipdoctest import skip_doctest
16 from IPython.testing.skipdoctest import skip_doctest
17 from IPython.utils.ipstruct import Struct
17 from IPython.utils.ipstruct import Struct
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 @skip_doctest
77 @skip_doctest
78 @magic_arguments.magic_arguments()
78 @magic_arguments.magic_arguments()
79 @magic_arguments.argument(
79 @magic_arguments.argument(
80 '-l', '--line', action='store_true',
80 '-l', '--line', action='store_true',
81 help="""Create a line magic alias."""
81 help="""Create a line magic alias."""
82 )
82 )
83 @magic_arguments.argument(
83 @magic_arguments.argument(
84 '-c', '--cell', action='store_true',
84 '-c', '--cell', action='store_true',
85 help="""Create a cell magic alias."""
85 help="""Create a cell magic alias."""
86 )
86 )
87 @magic_arguments.argument(
87 @magic_arguments.argument(
88 'name',
88 'name',
89 help="""Name of the magic to be created."""
89 help="""Name of the magic to be created."""
90 )
90 )
91 @magic_arguments.argument(
91 @magic_arguments.argument(
92 'target',
92 'target',
93 help="""Name of the existing line or cell magic."""
93 help="""Name of the existing line or cell magic."""
94 )
94 )
95 @magic_arguments.argument(
95 @magic_arguments.argument(
96 '-p', '--params', default=None,
96 '-p', '--params', default=None,
97 help="""Parameters passed to the magic function."""
97 help="""Parameters passed to the magic function."""
98 )
98 )
99 @line_magic
99 @line_magic
100 def alias_magic(self, line=''):
100 def alias_magic(self, line=''):
101 """Create an alias for an existing line or cell magic.
101 """Create an alias for an existing line or cell magic.
102
102
103 Examples
103 Examples
104 --------
104 --------
105 ::
105 ::
106
106
107 In [1]: %alias_magic t timeit
107 In [1]: %alias_magic t timeit
108 Created `%t` as an alias for `%timeit`.
108 Created `%t` as an alias for `%timeit`.
109 Created `%%t` as an alias for `%%timeit`.
109 Created `%%t` as an alias for `%%timeit`.
110
110
111 In [2]: %t -n1 pass
111 In [2]: %t -n1 pass
112 1 loops, best of 3: 954 ns per loop
112 1 loops, best of 3: 954 ns per loop
113
113
114 In [3]: %%t -n1
114 In [3]: %%t -n1
115 ...: pass
115 ...: pass
116 ...:
116 ...:
117 1 loops, best of 3: 954 ns per loop
117 1 loops, best of 3: 954 ns per loop
118
118
119 In [4]: %alias_magic --cell whereami pwd
119 In [4]: %alias_magic --cell whereami pwd
120 UsageError: Cell magic function `%%pwd` not found.
120 UsageError: Cell magic function `%%pwd` not found.
121 In [5]: %alias_magic --line whereami pwd
121 In [5]: %alias_magic --line whereami pwd
122 Created `%whereami` as an alias for `%pwd`.
122 Created `%whereami` as an alias for `%pwd`.
123
123
124 In [6]: %whereami
124 In [6]: %whereami
125 Out[6]: u'/home/testuser'
125 Out[6]: u'/home/testuser'
126
126
127 In [7]: %alias_magic h history "-p -l 30" --line
127 In [7]: %alias_magic h history "-p -l 30" --line
128 Created `%h` as an alias for `%history -l 30`.
128 Created `%h` as an alias for `%history -l 30`.
129 """
129 """
130
130
131 args = magic_arguments.parse_argstring(self.alias_magic, line)
131 args = magic_arguments.parse_argstring(self.alias_magic, line)
132 shell = self.shell
132 shell = self.shell
133 mman = self.shell.magics_manager
133 mman = self.shell.magics_manager
134 escs = ''.join(magic_escapes.values())
134 escs = ''.join(magic_escapes.values())
135
135
136 target = args.target.lstrip(escs)
136 target = args.target.lstrip(escs)
137 name = args.name.lstrip(escs)
137 name = args.name.lstrip(escs)
138
138
139 params = args.params
139 params = args.params
140 if (params and
140 if (params and
141 ((params.startswith('"') and params.endswith('"'))
141 ((params.startswith('"') and params.endswith('"'))
142 or (params.startswith("'") and params.endswith("'")))):
142 or (params.startswith("'") and params.endswith("'")))):
143 params = params[1:-1]
143 params = params[1:-1]
144
144
145 # Find the requested magics.
145 # Find the requested magics.
146 m_line = shell.find_magic(target, 'line')
146 m_line = shell.find_magic(target, 'line')
147 m_cell = shell.find_magic(target, 'cell')
147 m_cell = shell.find_magic(target, 'cell')
148 if args.line and m_line is None:
148 if args.line and m_line is None:
149 raise UsageError('Line magic function `%s%s` not found.' %
149 raise UsageError('Line magic function `%s%s` not found.' %
150 (magic_escapes['line'], target))
150 (magic_escapes['line'], target))
151 if args.cell and m_cell is None:
151 if args.cell and m_cell is None:
152 raise UsageError('Cell magic function `%s%s` not found.' %
152 raise UsageError('Cell magic function `%s%s` not found.' %
153 (magic_escapes['cell'], target))
153 (magic_escapes['cell'], target))
154
154
155 # If --line and --cell are not specified, default to the ones
155 # If --line and --cell are not specified, default to the ones
156 # that are available.
156 # that are available.
157 if not args.line and not args.cell:
157 if not args.line and not args.cell:
158 if not m_line and not m_cell:
158 if not m_line and not m_cell:
159 raise UsageError(
159 raise UsageError(
160 'No line or cell magic with name `%s` found.' % target
160 'No line or cell magic with name `%s` found.' % target
161 )
161 )
162 args.line = bool(m_line)
162 args.line = bool(m_line)
163 args.cell = bool(m_cell)
163 args.cell = bool(m_cell)
164
164
165 params_str = "" if params is None else " " + params
165 params_str = "" if params is None else " " + params
166
166
167 if args.line:
167 if args.line:
168 mman.register_alias(name, target, 'line', params)
168 mman.register_alias(name, target, 'line', params)
169 print('Created `%s%s` as an alias for `%s%s%s`.' % (
169 print('Created `%s%s` as an alias for `%s%s%s`.' % (
170 magic_escapes['line'], name,
170 magic_escapes['line'], name,
171 magic_escapes['line'], target, params_str))
171 magic_escapes['line'], target, params_str))
172
172
173 if args.cell:
173 if args.cell:
174 mman.register_alias(name, target, 'cell', params)
174 mman.register_alias(name, target, 'cell', params)
175 print('Created `%s%s` as an alias for `%s%s%s`.' % (
175 print('Created `%s%s` as an alias for `%s%s%s`.' % (
176 magic_escapes['cell'], name,
176 magic_escapes['cell'], name,
177 magic_escapes['cell'], target, params_str))
177 magic_escapes['cell'], target, params_str))
178
178
179 @line_magic
179 @line_magic
180 def lsmagic(self, parameter_s=''):
180 def lsmagic(self, parameter_s=''):
181 """List currently available magic functions."""
181 """List currently available magic functions."""
182 return MagicsDisplay(self.shell.magics_manager, ignore=[])
182 return MagicsDisplay(self.shell.magics_manager, ignore=[])
183
183
184 def _magic_docs(self, brief=False, rest=False):
184 def _magic_docs(self, brief=False, rest=False):
185 """Return docstrings from magic functions."""
185 """Return docstrings from magic functions."""
186 mman = self.shell.magics_manager
186 mman = self.shell.magics_manager
187 docs = mman.lsmagic_docs(brief, missing='No documentation')
187 docs = mman.lsmagic_docs(brief, missing='No documentation')
188
188
189 if rest:
189 if rest:
190 format_string = '**%s%s**::\n\n%s\n\n'
190 format_string = '**%s%s**::\n\n%s\n\n'
191 else:
191 else:
192 format_string = '%s%s:\n%s\n'
192 format_string = '%s%s:\n%s\n'
193
193
194 return ''.join(
194 return ''.join(
195 [format_string % (magic_escapes['line'], fname,
195 [format_string % (magic_escapes['line'], fname,
196 indent(dedent(fndoc)))
196 indent(dedent(fndoc)))
197 for fname, fndoc in sorted(docs['line'].items())]
197 for fname, fndoc in sorted(docs['line'].items())]
198 +
198 +
199 [format_string % (magic_escapes['cell'], fname,
199 [format_string % (magic_escapes['cell'], fname,
200 indent(dedent(fndoc)))
200 indent(dedent(fndoc)))
201 for fname, fndoc in sorted(docs['cell'].items())]
201 for fname, fndoc in sorted(docs['cell'].items())]
202 )
202 )
203
203
204 @line_magic
204 @line_magic
205 def magic(self, parameter_s=''):
205 def magic(self, parameter_s=''):
206 """Print information about the magic function system.
206 """Print information about the magic function system.
207
207
208 Supported formats: -latex, -brief, -rest
208 Supported formats: -latex, -brief, -rest
209 """
209 """
210
210
211 mode = ''
211 mode = ''
212 try:
212 try:
213 mode = parameter_s.split()[0][1:]
213 mode = parameter_s.split()[0][1:]
214 except IndexError:
214 except IndexError:
215 pass
215 pass
216
216
217 brief = (mode == 'brief')
217 brief = (mode == 'brief')
218 rest = (mode == 'rest')
218 rest = (mode == 'rest')
219 magic_docs = self._magic_docs(brief, rest)
219 magic_docs = self._magic_docs(brief, rest)
220
220
221 if mode == 'latex':
221 if mode == 'latex':
222 print(self.format_latex(magic_docs))
222 print(self.format_latex(magic_docs))
223 return
223 return
224 else:
224 else:
225 magic_docs = format_screen(magic_docs)
225 magic_docs = format_screen(magic_docs)
226
226
227 out = ["""
227 out = ["""
228 IPython's 'magic' functions
228 IPython's 'magic' functions
229 ===========================
229 ===========================
230
230
231 The magic function system provides a series of functions which allow you to
231 The magic function system provides a series of functions which allow you to
232 control the behavior of IPython itself, plus a lot of system-type
232 control the behavior of IPython itself, plus a lot of system-type
233 features. There are two kinds of magics, line-oriented and cell-oriented.
233 features. There are two kinds of magics, line-oriented and cell-oriented.
234
234
235 Line magics are prefixed with the % character and work much like OS
235 Line magics are prefixed with the % character and work much like OS
236 command-line calls: they get as an argument the rest of the line, where
236 command-line calls: they get as an argument the rest of the line, where
237 arguments are passed without parentheses or quotes. For example, this will
237 arguments are passed without parentheses or quotes. For example, this will
238 time the given statement::
238 time the given statement::
239
239
240 %timeit range(1000)
240 %timeit range(1000)
241
241
242 Cell magics are prefixed with a double %%, and they are functions that get as
242 Cell magics are prefixed with a double %%, and they are functions that get as
243 an argument not only the rest of the line, but also the lines below it in a
243 an argument not only the rest of the line, but also the lines below it in a
244 separate argument. These magics are called with two arguments: the rest of the
244 separate argument. These magics are called with two arguments: the rest of the
245 call line and the body of the cell, consisting of the lines below the first.
245 call line and the body of the cell, consisting of the lines below the first.
246 For example::
246 For example::
247
247
248 %%timeit x = numpy.random.randn((100, 100))
248 %%timeit x = numpy.random.randn((100, 100))
249 numpy.linalg.svd(x)
249 numpy.linalg.svd(x)
250
250
251 will time the execution of the numpy svd routine, running the assignment of x
251 will time the execution of the numpy svd routine, running the assignment of x
252 as part of the setup phase, which is not timed.
252 as part of the setup phase, which is not timed.
253
253
254 In a line-oriented client (the terminal or Qt console IPython), starting a new
254 In a line-oriented client (the terminal or Qt console IPython), starting a new
255 input with %% will automatically enter cell mode, and IPython will continue
255 input with %% will automatically enter cell mode, and IPython will continue
256 reading input until a blank line is given. In the notebook, simply type the
256 reading input until a blank line is given. In the notebook, simply type the
257 whole cell as one entity, but keep in mind that the %% escape can only be at
257 whole cell as one entity, but keep in mind that the %% escape can only be at
258 the very start of the cell.
258 the very start of the cell.
259
259
260 NOTE: If you have 'automagic' enabled (via the command line option or with the
260 NOTE: If you have 'automagic' enabled (via the command line option or with the
261 %automagic function), you don't need to type in the % explicitly for line
261 %automagic function), you don't need to type in the % explicitly for line
262 magics; cell magics always require an explicit '%%' escape. By default,
262 magics; cell magics always require an explicit '%%' escape. By default,
263 IPython ships with automagic on, so you should only rarely need the % escape.
263 IPython ships with automagic on, so you should only rarely need the % escape.
264
264
265 Example: typing '%cd mydir' (without the quotes) changes your working directory
265 Example: typing '%cd mydir' (without the quotes) changes your working directory
266 to 'mydir', if it exists.
266 to 'mydir', if it exists.
267
267
268 For a list of the available magic functions, use %lsmagic. For a description
268 For a list of the available magic functions, use %lsmagic. For a description
269 of any of them, type %magic_name?, e.g. '%cd?'.
269 of any of them, type %magic_name?, e.g. '%cd?'.
270
270
271 Currently the magic system has the following functions:""",
271 Currently the magic system has the following functions:""",
272 magic_docs,
272 magic_docs,
273 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
273 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
274 str(self.lsmagic()),
274 str(self.lsmagic()),
275 ]
275 ]
276 page.page('\n'.join(out))
276 page.page('\n'.join(out))
277
277
278
278
279 @line_magic
279 @line_magic
280 def page(self, parameter_s=''):
280 def page(self, parameter_s=''):
281 """Pretty print the object and display it through a pager.
281 """Pretty print the object and display it through a pager.
282
282
283 %page [options] OBJECT
283 %page [options] OBJECT
284
284
285 If no object is given, use _ (last output).
285 If no object is given, use _ (last output).
286
286
287 Options:
287 Options:
288
288
289 -r: page str(object), don't pretty-print it."""
289 -r: page str(object), don't pretty-print it."""
290
290
291 # After a function contributed by Olivier Aubert, slightly modified.
291 # After a function contributed by Olivier Aubert, slightly modified.
292
292
293 # Process options/args
293 # Process options/args
294 opts, args = self.parse_options(parameter_s, 'r')
294 opts, args = self.parse_options(parameter_s, 'r')
295 raw = 'r' in opts
295 raw = 'r' in opts
296
296
297 oname = args and args or '_'
297 oname = args and args or '_'
298 info = self.shell._ofind(oname)
298 info = self.shell._ofind(oname)
299 if info['found']:
299 if info['found']:
300 txt = (raw and str or pformat)( info['obj'] )
300 txt = (raw and str or pformat)( info['obj'] )
301 page.page(txt)
301 page.page(txt)
302 else:
302 else:
303 print('Object `%s` not found' % oname)
303 print('Object `%s` not found' % oname)
304
304
305 @line_magic
305 @line_magic
306 def pprint(self, parameter_s=''):
306 def pprint(self, parameter_s=''):
307 """Toggle pretty printing on/off."""
307 """Toggle pretty printing on/off."""
308 ptformatter = self.shell.display_formatter.formatters['text/plain']
308 ptformatter = self.shell.display_formatter.formatters['text/plain']
309 ptformatter.pprint = bool(1 - ptformatter.pprint)
309 ptformatter.pprint = bool(1 - ptformatter.pprint)
310 print('Pretty printing has been turned',
310 print('Pretty printing has been turned',
311 ['OFF','ON'][ptformatter.pprint])
311 ['OFF','ON'][ptformatter.pprint])
312
312
313 @line_magic
313 @line_magic
314 def colors(self, parameter_s=''):
314 def colors(self, parameter_s=''):
315 """Switch color scheme for prompts, info system and exception handlers.
315 """Switch color scheme for prompts, info system and exception handlers.
316
316
317 Currently implemented schemes: NoColor, Linux, LightBG.
317 Currently implemented schemes: NoColor, Linux, LightBG.
318
318
319 Color scheme names are not case-sensitive.
319 Color scheme names are not case-sensitive.
320
320
321 Examples
321 Examples
322 --------
322 --------
323 To get a plain black and white terminal::
323 To get a plain black and white terminal::
324
324
325 %colors nocolor
325 %colors nocolor
326 """
326 """
327 def color_switch_err(name):
327 def color_switch_err(name):
328 warn('Error changing %s color schemes.\n%s' %
328 warn('Error changing %s color schemes.\n%s' %
329 (name, sys.exc_info()[1]), stacklevel=2)
329 (name, sys.exc_info()[1]), stacklevel=2)
330
330
331
331
332 new_scheme = parameter_s.strip()
332 new_scheme = parameter_s.strip()
333 if not new_scheme:
333 if not new_scheme:
334 raise UsageError(
334 raise UsageError(
335 "%colors: you must specify a color scheme. See '%colors?'")
335 "%colors: you must specify a color scheme. See '%colors?'")
336 # local shortcut
336 # local shortcut
337 shell = self.shell
337 shell = self.shell
338
338
339 # Set shell colour scheme
339 # Set shell colour scheme
340 try:
340 try:
341 shell.colors = new_scheme
341 shell.colors = new_scheme
342 shell.refresh_style()
342 shell.refresh_style()
343 except:
343 except:
344 color_switch_err('shell')
344 color_switch_err('shell')
345
345
346 # Set exception colors
346 # Set exception colors
347 try:
347 try:
348 shell.InteractiveTB.set_colors(scheme = new_scheme)
348 shell.InteractiveTB.set_colors(scheme = new_scheme)
349 shell.SyntaxTB.set_colors(scheme = new_scheme)
349 shell.SyntaxTB.set_colors(scheme = new_scheme)
350 except:
350 except:
351 color_switch_err('exception')
351 color_switch_err('exception')
352
352
353 # Set info (for 'object?') colors
353 # Set info (for 'object?') colors
354 if shell.color_info:
354 if shell.color_info:
355 try:
355 try:
356 shell.inspector.set_active_scheme(new_scheme)
356 shell.inspector.set_active_scheme(new_scheme)
357 except:
357 except:
358 color_switch_err('object inspector')
358 color_switch_err('object inspector')
359 else:
359 else:
360 shell.inspector.set_active_scheme('NoColor')
360 shell.inspector.set_active_scheme('NoColor')
361
361
362 @line_magic
362 @line_magic
363 def xmode(self, parameter_s=''):
363 def xmode(self, parameter_s=''):
364 """Switch modes for the exception handlers.
364 """Switch modes for the exception handlers.
365
365
366 Valid modes: Plain, Context, Verbose, and Minimal.
366 Valid modes: Plain, Context, Verbose, and Minimal.
367
367
368 If called without arguments, acts as a toggle.
368 If called without arguments, acts as a toggle.
369
369
370 When in verbose mode the value --show (and --hide)
370 When in verbose mode the value --show (and --hide)
371 will respectively show (or hide) frames with ``__tracebackhide__ =
371 will respectively show (or hide) frames with ``__tracebackhide__ =
372 True`` value set.
372 True`` value set.
373 """
373 """
374
374
375 def xmode_switch_err(name):
375 def xmode_switch_err(name):
376 warn('Error changing %s exception modes.\n%s' %
376 warn('Error changing %s exception modes.\n%s' %
377 (name,sys.exc_info()[1]))
377 (name,sys.exc_info()[1]))
378
378
379 shell = self.shell
379 shell = self.shell
380 if parameter_s.strip() == "--show":
380 if parameter_s.strip() == "--show":
381 shell.InteractiveTB.skip_hidden = False
381 shell.InteractiveTB.skip_hidden = False
382 return
382 return
383 if parameter_s.strip() == "--hide":
383 if parameter_s.strip() == "--hide":
384 shell.InteractiveTB.skip_hidden = True
384 shell.InteractiveTB.skip_hidden = True
385 return
385 return
386
386
387 new_mode = parameter_s.strip().capitalize()
387 new_mode = parameter_s.strip().capitalize()
388 try:
388 try:
389 shell.InteractiveTB.set_mode(mode=new_mode)
389 shell.InteractiveTB.set_mode(mode=new_mode)
390 print('Exception reporting mode:',shell.InteractiveTB.mode)
390 print('Exception reporting mode:',shell.InteractiveTB.mode)
391 except:
391 except:
392 xmode_switch_err('user')
392 xmode_switch_err('user')
393
393
394 @line_magic
394 @line_magic
395 def quickref(self, arg):
395 def quickref(self, arg):
396 """ Show a quick reference sheet """
396 """ Show a quick reference sheet """
397 from IPython.core.usage import quick_reference
397 from IPython.core.usage import quick_reference
398 qr = quick_reference + self._magic_docs(brief=True)
398 qr = quick_reference + self._magic_docs(brief=True)
399 page.page(qr)
399 page.page(qr)
400
400
401 @line_magic
401 @line_magic
402 def doctest_mode(self, parameter_s=''):
402 def doctest_mode(self, parameter_s=''):
403 """Toggle doctest mode on and off.
403 """Toggle doctest mode on and off.
404
404
405 This mode is intended to make IPython behave as much as possible like a
405 This mode is intended to make IPython behave as much as possible like a
406 plain Python shell, from the perspective of how its prompts, exceptions
406 plain Python shell, from the perspective of how its prompts, exceptions
407 and output look. This makes it easy to copy and paste parts of a
407 and output look. This makes it easy to copy and paste parts of a
408 session into doctests. It does so by:
408 session into doctests. It does so by:
409
409
410 - Changing the prompts to the classic ``>>>`` ones.
410 - Changing the prompts to the classic ``>>>`` ones.
411 - Changing the exception reporting mode to 'Plain'.
411 - Changing the exception reporting mode to 'Plain'.
412 - Disabling pretty-printing of output.
412 - Disabling pretty-printing of output.
413
413
414 Note that IPython also supports the pasting of code snippets that have
414 Note that IPython also supports the pasting of code snippets that have
415 leading '>>>' and '...' prompts in them. This means that you can paste
415 leading '>>>' and '...' prompts in them. This means that you can paste
416 doctests from files or docstrings (even if they have leading
416 doctests from files or docstrings (even if they have leading
417 whitespace), and the code will execute correctly. You can then use
417 whitespace), and the code will execute correctly. You can then use
418 '%history -t' to see the translated history; this will give you the
418 '%history -t' to see the translated history; this will give you the
419 input after removal of all the leading prompts and whitespace, which
419 input after removal of all the leading prompts and whitespace, which
420 can be pasted back into an editor.
420 can be pasted back into an editor.
421
421
422 With these features, you can switch into this mode easily whenever you
422 With these features, you can switch into this mode easily whenever you
423 need to do testing and changes to doctests, without having to leave
423 need to do testing and changes to doctests, without having to leave
424 your existing IPython session.
424 your existing IPython session.
425 """
425 """
426
426
427 # Shorthands
427 # Shorthands
428 shell = self.shell
428 shell = self.shell
429 meta = shell.meta
429 meta = shell.meta
430 disp_formatter = self.shell.display_formatter
430 disp_formatter = self.shell.display_formatter
431 ptformatter = disp_formatter.formatters['text/plain']
431 ptformatter = disp_formatter.formatters['text/plain']
432 # dstore is a data store kept in the instance metadata bag to track any
432 # dstore is a data store kept in the instance metadata bag to track any
433 # changes we make, so we can undo them later.
433 # changes we make, so we can undo them later.
434 dstore = meta.setdefault('doctest_mode',Struct())
434 dstore = meta.setdefault('doctest_mode',Struct())
435 save_dstore = dstore.setdefault
435 save_dstore = dstore.setdefault
436
436
437 # save a few values we'll need to recover later
437 # save a few values we'll need to recover later
438 mode = save_dstore('mode',False)
438 mode = save_dstore('mode',False)
439 save_dstore('rc_pprint',ptformatter.pprint)
439 save_dstore('rc_pprint',ptformatter.pprint)
440 save_dstore('xmode',shell.InteractiveTB.mode)
440 save_dstore('xmode',shell.InteractiveTB.mode)
441 save_dstore('rc_separate_out',shell.separate_out)
441 save_dstore('rc_separate_out',shell.separate_out)
442 save_dstore('rc_separate_out2',shell.separate_out2)
442 save_dstore('rc_separate_out2',shell.separate_out2)
443 save_dstore('rc_separate_in',shell.separate_in)
443 save_dstore('rc_separate_in',shell.separate_in)
444 save_dstore('rc_active_types',disp_formatter.active_types)
444 save_dstore('rc_active_types',disp_formatter.active_types)
445
445
446 if not mode:
446 if not mode:
447 # turn on
447 # turn on
448
448
449 # Prompt separators like plain python
449 # Prompt separators like plain python
450 shell.separate_in = ''
450 shell.separate_in = ''
451 shell.separate_out = ''
451 shell.separate_out = ''
452 shell.separate_out2 = ''
452 shell.separate_out2 = ''
453
453
454
454
455 ptformatter.pprint = False
455 ptformatter.pprint = False
456 disp_formatter.active_types = ['text/plain']
456 disp_formatter.active_types = ['text/plain']
457
457
458 shell.magic('xmode Plain')
458 shell.magic('xmode Plain')
459 else:
459 else:
460 # turn off
460 # turn off
461 shell.separate_in = dstore.rc_separate_in
461 shell.separate_in = dstore.rc_separate_in
462
462
463 shell.separate_out = dstore.rc_separate_out
463 shell.separate_out = dstore.rc_separate_out
464 shell.separate_out2 = dstore.rc_separate_out2
464 shell.separate_out2 = dstore.rc_separate_out2
465
465
466 ptformatter.pprint = dstore.rc_pprint
466 ptformatter.pprint = dstore.rc_pprint
467 disp_formatter.active_types = dstore.rc_active_types
467 disp_formatter.active_types = dstore.rc_active_types
468
468
469 shell.magic('xmode ' + dstore.xmode)
469 shell.magic('xmode ' + dstore.xmode)
470
470
471 # mode here is the state before we switch; switch_doctest_mode takes
471 # mode here is the state before we switch; switch_doctest_mode takes
472 # the mode we're switching to.
472 # the mode we're switching to.
473 shell.switch_doctest_mode(not mode)
473 shell.switch_doctest_mode(not mode)
474
474
475 # Store new mode and inform
475 # Store new mode and inform
476 dstore.mode = bool(not mode)
476 dstore.mode = bool(not mode)
477 mode_label = ['OFF','ON'][dstore.mode]
477 mode_label = ['OFF','ON'][dstore.mode]
478 print('Doctest mode is:', mode_label)
478 print('Doctest mode is:', mode_label)
479
479
480 @line_magic
480 @line_magic
481 def gui(self, parameter_s=''):
481 def gui(self, parameter_s=''):
482 """Enable or disable IPython GUI event loop integration.
482 """Enable or disable IPython GUI event loop integration.
483
483
484 %gui [GUINAME]
484 %gui [GUINAME]
485
485
486 This magic replaces IPython's threaded shells that were activated
486 This magic replaces IPython's threaded shells that were activated
487 using the (pylab/wthread/etc.) command line flags. GUI toolkits
487 using the (pylab/wthread/etc.) command line flags. GUI toolkits
488 can now be enabled at runtime and keyboard
488 can now be enabled at runtime and keyboard
489 interrupts should work without any problems. The following toolkits
489 interrupts should work without any problems. The following toolkits
490 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
490 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
491
491
492 %gui wx # enable wxPython event loop integration
492 %gui wx # enable wxPython event loop integration
493 %gui qt4|qt # enable PyQt4 event loop integration
493 %gui qt4|qt # enable PyQt4 event loop integration
494 %gui qt5 # enable PyQt5 event loop integration
494 %gui qt5 # enable PyQt5 event loop integration
495 %gui gtk # enable PyGTK event loop integration
495 %gui gtk # enable PyGTK event loop integration
496 %gui gtk3 # enable Gtk3 event loop integration
496 %gui gtk3 # enable Gtk3 event loop integration
497 %gui gtk4 # enable Gtk4 event loop integration
497 %gui gtk4 # enable Gtk4 event loop integration
498 %gui tk # enable Tk event loop integration
498 %gui tk # enable Tk event loop integration
499 %gui osx # enable Cocoa event loop integration
499 %gui osx # enable Cocoa event loop integration
500 # (requires %matplotlib 1.1)
500 # (requires %matplotlib 1.1)
501 %gui # disable all event loop integration
501 %gui # disable all event loop integration
502
502
503 WARNING: after any of these has been called you can simply create
503 WARNING: after any of these has been called you can simply create
504 an application object, but DO NOT start the event loop yourself, as
504 an application object, but DO NOT start the event loop yourself, as
505 we have already handled that.
505 we have already handled that.
506 """
506 """
507 opts, arg = self.parse_options(parameter_s, '')
507 opts, arg = self.parse_options(parameter_s, '')
508 if arg=='': arg = None
508 if arg=='': arg = None
509 try:
509 try:
510 return self.shell.enable_gui(arg)
510 return self.shell.enable_gui(arg)
511 except Exception as e:
511 except Exception as e:
512 # print simple error message, rather than traceback if we can't
512 # print simple error message, rather than traceback if we can't
513 # hook up the GUI
513 # hook up the GUI
514 error(str(e))
514 error(str(e))
515
515
516 @skip_doctest
516 @skip_doctest
517 @line_magic
517 @line_magic
518 def precision(self, s=''):
518 def precision(self, s=''):
519 """Set floating point precision for pretty printing.
519 """Set floating point precision for pretty printing.
520
520
521 Can set either integer precision or a format string.
521 Can set either integer precision or a format string.
522
522
523 If numpy has been imported and precision is an int,
523 If numpy has been imported and precision is an int,
524 numpy display precision will also be set, via ``numpy.set_printoptions``.
524 numpy display precision will also be set, via ``numpy.set_printoptions``.
525
525
526 If no argument is given, defaults will be restored.
526 If no argument is given, defaults will be restored.
527
527
528 Examples
528 Examples
529 --------
529 --------
530 ::
530 ::
531
531
532 In [1]: from math import pi
532 In [1]: from math import pi
533
533
534 In [2]: %precision 3
534 In [2]: %precision 3
535 Out[2]: u'%.3f'
535 Out[2]: u'%.3f'
536
536
537 In [3]: pi
537 In [3]: pi
538 Out[3]: 3.142
538 Out[3]: 3.142
539
539
540 In [4]: %precision %i
540 In [4]: %precision %i
541 Out[4]: u'%i'
541 Out[4]: u'%i'
542
542
543 In [5]: pi
543 In [5]: pi
544 Out[5]: 3
544 Out[5]: 3
545
545
546 In [6]: %precision %e
546 In [6]: %precision %e
547 Out[6]: u'%e'
547 Out[6]: u'%e'
548
548
549 In [7]: pi**10
549 In [7]: pi**10
550 Out[7]: 9.364805e+04
550 Out[7]: 9.364805e+04
551
551
552 In [8]: %precision
552 In [8]: %precision
553 Out[8]: u'%r'
553 Out[8]: u'%r'
554
554
555 In [9]: pi**10
555 In [9]: pi**10
556 Out[9]: 93648.047476082982
556 Out[9]: 93648.047476082982
557 """
557 """
558 ptformatter = self.shell.display_formatter.formatters['text/plain']
558 ptformatter = self.shell.display_formatter.formatters['text/plain']
559 ptformatter.float_precision = s
559 ptformatter.float_precision = s
560 return ptformatter.float_format
560 return ptformatter.float_format
561
561
562 @magic_arguments.magic_arguments()
562 @magic_arguments.magic_arguments()
563 @magic_arguments.argument(
563 @magic_arguments.argument(
564 'filename', type=str,
564 'filename', type=str,
565 help='Notebook name or filename'
565 help='Notebook name or filename'
566 )
566 )
567 @line_magic
567 @line_magic
568 def notebook(self, s):
568 def notebook(self, s):
569 """Export and convert IPython notebooks.
569 """Export and convert IPython notebooks.
570
570
571 This function can export the current IPython history to a notebook file.
571 This function can export the current IPython history to a notebook file.
572 For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".
572 For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".
573 """
573 """
574 args = magic_arguments.parse_argstring(self.notebook, s)
574 args = magic_arguments.parse_argstring(self.notebook, s)
575
575
576 from nbformat import write, v4
576 from nbformat import write, v4
577
577
578 cells = []
578 cells = []
579 hist = list(self.shell.history_manager.get_range())
579 hist = list(self.shell.history_manager.get_range())
580 if(len(hist)<=1):
580 if(len(hist)<=1):
581 raise ValueError('History is empty, cannot export')
581 raise ValueError('History is empty, cannot export')
582 for session, execution_count, source in hist[:-1]:
582 for session, execution_count, source in hist[:-1]:
583 cells.append(v4.new_code_cell(
583 cells.append(v4.new_code_cell(
584 execution_count=execution_count,
584 execution_count=execution_count,
585 source=source
585 source=source
586 ))
586 ))
587 nb = v4.new_notebook(cells=cells)
587 nb = v4.new_notebook(cells=cells)
588 with io.open(args.filename, 'w', encoding='utf-8') as f:
588 with io.open(args.filename, 'w', encoding='utf-8') as f:
589 write(nb, f, version=4)
589 write(nb, f, version=4)
590
590
591 @magics_class
591 @magics_class
592 class AsyncMagics(BasicMagics):
592 class AsyncMagics(BasicMagics):
593
593
594 @line_magic
594 @line_magic
595 def autoawait(self, parameter_s):
595 def autoawait(self, parameter_s):
596 """
596 """
597 Allow to change the status of the autoawait option.
597 Allow to change the status of the autoawait option.
598
598
599 This allow you to set a specific asynchronous code runner.
599 This allow you to set a specific asynchronous code runner.
600
600
601 If no value is passed, print the currently used asynchronous integration
601 If no value is passed, print the currently used asynchronous integration
602 and whether it is activated.
602 and whether it is activated.
603
603
604 It can take a number of value evaluated in the following order:
604 It can take a number of value evaluated in the following order:
605
605
606 - False/false/off deactivate autoawait integration
606 - False/false/off deactivate autoawait integration
607 - True/true/on activate autoawait integration using configured default
607 - True/true/on activate autoawait integration using configured default
608 loop
608 loop
609 - asyncio/curio/trio activate autoawait integration and use integration
609 - asyncio/curio/trio activate autoawait integration and use integration
610 with said library.
610 with said library.
611
611
612 - `sync` turn on the pseudo-sync integration (mostly used for
612 - `sync` turn on the pseudo-sync integration (mostly used for
613 `IPython.embed()` which does not run IPython with a real eventloop and
613 `IPython.embed()` which does not run IPython with a real eventloop and
614 deactivate running asynchronous code. Turning on Asynchronous code with
614 deactivate running asynchronous code. Turning on Asynchronous code with
615 the pseudo sync loop is undefined behavior and may lead IPython to crash.
615 the pseudo sync loop is undefined behavior and may lead IPython to crash.
616
616
617 If the passed parameter does not match any of the above and is a python
617 If the passed parameter does not match any of the above and is a python
618 identifier, get said object from user namespace and set it as the
618 identifier, get said object from user namespace and set it as the
619 runner, and activate autoawait.
619 runner, and activate autoawait.
620
620
621 If the object is a fully qualified object name, attempt to import it and
621 If the object is a fully qualified object name, attempt to import it and
622 set it as the runner, and activate autoawait.
622 set it as the runner, and activate autoawait.
623
623
624
625 The exact behavior of autoawait is experimental and subject to change
624 The exact behavior of autoawait is experimental and subject to change
626 across version of IPython and Python.
625 across version of IPython and Python.
627 """
626 """
628
627
629 param = parameter_s.strip()
628 param = parameter_s.strip()
630 d = {True: "on", False: "off"}
629 d = {True: "on", False: "off"}
631
630
632 if not param:
631 if not param:
633 print("IPython autoawait is `{}`, and set to use `{}`".format(
632 print("IPython autoawait is `{}`, and set to use `{}`".format(
634 d[self.shell.autoawait],
633 d[self.shell.autoawait],
635 self.shell.loop_runner
634 self.shell.loop_runner
636 ))
635 ))
637 return None
636 return None
638
637
639 if param.lower() in ('false', 'off'):
638 if param.lower() in ('false', 'off'):
640 self.shell.autoawait = False
639 self.shell.autoawait = False
641 return None
640 return None
642 if param.lower() in ('true', 'on'):
641 if param.lower() in ('true', 'on'):
643 self.shell.autoawait = True
642 self.shell.autoawait = True
644 return None
643 return None
645
644
646 if param in self.shell.loop_runner_map:
645 if param in self.shell.loop_runner_map:
647 self.shell.loop_runner, self.shell.autoawait = self.shell.loop_runner_map[param]
646 self.shell.loop_runner, self.shell.autoawait = self.shell.loop_runner_map[param]
648 return None
647 return None
649
648
650 if param in self.shell.user_ns :
649 if param in self.shell.user_ns :
651 self.shell.loop_runner = self.shell.user_ns[param]
650 self.shell.loop_runner = self.shell.user_ns[param]
652 self.shell.autoawait = True
651 self.shell.autoawait = True
653 return None
652 return None
654
653
655 runner = import_item(param)
654 runner = import_item(param)
656
655
657 self.shell.loop_runner = runner
656 self.shell.loop_runner = runner
658 self.shell.autoawait = True
657 self.shell.autoawait = True
@@ -1,1509 +1,1507 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Implementation of execution-related magic functions."""
2 """Implementation of execution-related magic functions."""
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6
6
7
7
8 import ast
8 import ast
9 import bdb
9 import bdb
10 import builtins as builtin_mod
10 import builtins as builtin_mod
11 import cProfile as profile
11 import cProfile as profile
12 import gc
12 import gc
13 import itertools
13 import itertools
14 import math
14 import math
15 import os
15 import os
16 import pstats
16 import pstats
17 import re
17 import re
18 import shlex
18 import shlex
19 import sys
19 import sys
20 import time
20 import time
21 import timeit
21 import timeit
22 from ast import Module
22 from ast import Module
23 from io import StringIO
23 from io import StringIO
24 from logging import error
24 from logging import error
25 from pathlib import Path
25 from pathlib import Path
26 from pdb import Restart
26 from pdb import Restart
27 from warnings import warn
27 from warnings import warn
28
28
29 from IPython.core import magic_arguments, oinspect, page
29 from IPython.core import magic_arguments, oinspect, page
30 from IPython.core.error import UsageError
30 from IPython.core.error import UsageError
31 from IPython.core.macro import Macro
31 from IPython.core.macro import Macro
32 from IPython.core.magic import (
32 from IPython.core.magic import (
33 Magics,
33 Magics,
34 cell_magic,
34 cell_magic,
35 line_cell_magic,
35 line_cell_magic,
36 line_magic,
36 line_magic,
37 magics_class,
37 magics_class,
38 needs_local_scope,
38 needs_local_scope,
39 no_var_expand,
39 no_var_expand,
40 on_off,
40 on_off,
41 )
41 )
42 from IPython.testing.skipdoctest import skip_doctest
42 from IPython.testing.skipdoctest import skip_doctest
43 from IPython.utils.capture import capture_output
43 from IPython.utils.capture import capture_output
44 from IPython.utils.contexts import preserve_keys
44 from IPython.utils.contexts import preserve_keys
45 from IPython.utils.ipstruct import Struct
45 from IPython.utils.ipstruct import Struct
46 from IPython.utils.module_paths import find_mod
46 from IPython.utils.module_paths import find_mod
47 from IPython.utils.path import get_py_filename, shellglob
47 from IPython.utils.path import get_py_filename, shellglob
48 from IPython.utils.timing import clock, clock2
48 from IPython.utils.timing import clock, clock2
49
49
50 #-----------------------------------------------------------------------------
50 #-----------------------------------------------------------------------------
51 # Magic implementation classes
51 # Magic implementation classes
52 #-----------------------------------------------------------------------------
52 #-----------------------------------------------------------------------------
53
53
54
54
55 class TimeitResult(object):
55 class TimeitResult(object):
56 """
56 """
57 Object returned by the timeit magic with info about the run.
57 Object returned by the timeit magic with info about the run.
58
58
59 Contains the following attributes :
59 Contains the following attributes :
60
60
61 loops: (int) number of loops done per measurement
61 loops: (int) number of loops done per measurement
62 repeat: (int) number of times the measurement has been repeated
62 repeat: (int) number of times the measurement has been repeated
63 best: (float) best execution time / number
63 best: (float) best execution time / number
64 all_runs: (list of float) execution time of each run (in s)
64 all_runs: (list of float) execution time of each run (in s)
65 compile_time: (float) time of statement compilation (s)
65 compile_time: (float) time of statement compilation (s)
66
66
67 """
67 """
68 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
68 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
69 self.loops = loops
69 self.loops = loops
70 self.repeat = repeat
70 self.repeat = repeat
71 self.best = best
71 self.best = best
72 self.worst = worst
72 self.worst = worst
73 self.all_runs = all_runs
73 self.all_runs = all_runs
74 self.compile_time = compile_time
74 self.compile_time = compile_time
75 self._precision = precision
75 self._precision = precision
76 self.timings = [ dt / self.loops for dt in all_runs]
76 self.timings = [ dt / self.loops for dt in all_runs]
77
77
78 @property
78 @property
79 def average(self):
79 def average(self):
80 return math.fsum(self.timings) / len(self.timings)
80 return math.fsum(self.timings) / len(self.timings)
81
81
82 @property
82 @property
83 def stdev(self):
83 def stdev(self):
84 mean = self.average
84 mean = self.average
85 return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5
85 return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5
86
86
87 def __str__(self):
87 def __str__(self):
88 pm = '+-'
88 pm = '+-'
89 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
89 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
90 try:
90 try:
91 u'\xb1'.encode(sys.stdout.encoding)
91 u'\xb1'.encode(sys.stdout.encoding)
92 pm = u'\xb1'
92 pm = u'\xb1'
93 except:
93 except:
94 pass
94 pass
95 return "{mean} {pm} {std} per loop (mean {pm} std. dev. of {runs} run{run_plural}, {loops:,} loop{loop_plural} each)".format(
95 return "{mean} {pm} {std} per loop (mean {pm} std. dev. of {runs} run{run_plural}, {loops:,} loop{loop_plural} each)".format(
96 pm=pm,
96 pm=pm,
97 runs=self.repeat,
97 runs=self.repeat,
98 loops=self.loops,
98 loops=self.loops,
99 loop_plural="" if self.loops == 1 else "s",
99 loop_plural="" if self.loops == 1 else "s",
100 run_plural="" if self.repeat == 1 else "s",
100 run_plural="" if self.repeat == 1 else "s",
101 mean=_format_time(self.average, self._precision),
101 mean=_format_time(self.average, self._precision),
102 std=_format_time(self.stdev, self._precision),
102 std=_format_time(self.stdev, self._precision),
103 )
103 )
104
104
105 def _repr_pretty_(self, p , cycle):
105 def _repr_pretty_(self, p , cycle):
106 unic = self.__str__()
106 unic = self.__str__()
107 p.text(u'<TimeitResult : '+unic+u'>')
107 p.text(u'<TimeitResult : '+unic+u'>')
108
108
109
109
110 class TimeitTemplateFiller(ast.NodeTransformer):
110 class TimeitTemplateFiller(ast.NodeTransformer):
111 """Fill in the AST template for timing execution.
111 """Fill in the AST template for timing execution.
112
112
113 This is quite closely tied to the template definition, which is in
113 This is quite closely tied to the template definition, which is in
114 :meth:`ExecutionMagics.timeit`.
114 :meth:`ExecutionMagics.timeit`.
115 """
115 """
116 def __init__(self, ast_setup, ast_stmt):
116 def __init__(self, ast_setup, ast_stmt):
117 self.ast_setup = ast_setup
117 self.ast_setup = ast_setup
118 self.ast_stmt = ast_stmt
118 self.ast_stmt = ast_stmt
119
119
120 def visit_FunctionDef(self, node):
120 def visit_FunctionDef(self, node):
121 "Fill in the setup statement"
121 "Fill in the setup statement"
122 self.generic_visit(node)
122 self.generic_visit(node)
123 if node.name == "inner":
123 if node.name == "inner":
124 node.body[:1] = self.ast_setup.body
124 node.body[:1] = self.ast_setup.body
125
125
126 return node
126 return node
127
127
128 def visit_For(self, node):
128 def visit_For(self, node):
129 "Fill in the statement to be timed"
129 "Fill in the statement to be timed"
130 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
130 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
131 node.body = self.ast_stmt.body
131 node.body = self.ast_stmt.body
132 return node
132 return node
133
133
134
134
135 class Timer(timeit.Timer):
135 class Timer(timeit.Timer):
136 """Timer class that explicitly uses self.inner
136 """Timer class that explicitly uses self.inner
137
137
138 which is an undocumented implementation detail of CPython,
138 which is an undocumented implementation detail of CPython,
139 not shared by PyPy.
139 not shared by PyPy.
140 """
140 """
141 # Timer.timeit copied from CPython 3.4.2
141 # Timer.timeit copied from CPython 3.4.2
142 def timeit(self, number=timeit.default_number):
142 def timeit(self, number=timeit.default_number):
143 """Time 'number' executions of the main statement.
143 """Time 'number' executions of the main statement.
144
144
145 To be precise, this executes the setup statement once, and
145 To be precise, this executes the setup statement once, and
146 then returns the time it takes to execute the main statement
146 then returns the time it takes to execute the main statement
147 a number of times, as a float measured in seconds. The
147 a number of times, as a float measured in seconds. The
148 argument is the number of times through the loop, defaulting
148 argument is the number of times through the loop, defaulting
149 to one million. The main statement, the setup statement and
149 to one million. The main statement, the setup statement and
150 the timer function to be used are passed to the constructor.
150 the timer function to be used are passed to the constructor.
151 """
151 """
152 it = itertools.repeat(None, number)
152 it = itertools.repeat(None, number)
153 gcold = gc.isenabled()
153 gcold = gc.isenabled()
154 gc.disable()
154 gc.disable()
155 try:
155 try:
156 timing = self.inner(it, self.timer)
156 timing = self.inner(it, self.timer)
157 finally:
157 finally:
158 if gcold:
158 if gcold:
159 gc.enable()
159 gc.enable()
160 return timing
160 return timing
161
161
162
162
163 @magics_class
163 @magics_class
164 class ExecutionMagics(Magics):
164 class ExecutionMagics(Magics):
165 """Magics related to code execution, debugging, profiling, etc.
165 """Magics related to code execution, debugging, profiling, etc.
166
166
167 """
167 """
168
168
169 def __init__(self, shell):
169 def __init__(self, shell):
170 super(ExecutionMagics, self).__init__(shell)
170 super(ExecutionMagics, self).__init__(shell)
171 # Default execution function used to actually run user code.
171 # Default execution function used to actually run user code.
172 self.default_runner = None
172 self.default_runner = None
173
173
174 @skip_doctest
174 @skip_doctest
175 @no_var_expand
175 @no_var_expand
176 @line_cell_magic
176 @line_cell_magic
177 def prun(self, parameter_s='', cell=None):
177 def prun(self, parameter_s='', cell=None):
178
178
179 """Run a statement through the python code profiler.
179 """Run a statement through the python code profiler.
180
180
181 Usage, in line mode:
181 Usage, in line mode:
182 %prun [options] statement
182 %prun [options] statement
183
183
184 Usage, in cell mode:
184 Usage, in cell mode:
185 %%prun [options] [statement]
185 %%prun [options] [statement]
186 code...
186 code...
187 code...
187 code...
188
188
189 In cell mode, the additional code lines are appended to the (possibly
189 In cell mode, the additional code lines are appended to the (possibly
190 empty) statement in the first line. Cell mode allows you to easily
190 empty) statement in the first line. Cell mode allows you to easily
191 profile multiline blocks without having to put them in a separate
191 profile multiline blocks without having to put them in a separate
192 function.
192 function.
193
193
194 The given statement (which doesn't require quote marks) is run via the
194 The given statement (which doesn't require quote marks) is run via the
195 python profiler in a manner similar to the profile.run() function.
195 python profiler in a manner similar to the profile.run() function.
196 Namespaces are internally managed to work correctly; profile.run
196 Namespaces are internally managed to work correctly; profile.run
197 cannot be used in IPython because it makes certain assumptions about
197 cannot be used in IPython because it makes certain assumptions about
198 namespaces which do not hold under IPython.
198 namespaces which do not hold under IPython.
199
199
200 Options:
200 Options:
201
201
202 -l <limit>
202 -l <limit>
203 you can place restrictions on what or how much of the
203 you can place restrictions on what or how much of the
204 profile gets printed. The limit value can be:
204 profile gets printed. The limit value can be:
205
205
206 * A string: only information for function names containing this string
206 * A string: only information for function names containing this string
207 is printed.
207 is printed.
208
208
209 * An integer: only these many lines are printed.
209 * An integer: only these many lines are printed.
210
210
211 * A float (between 0 and 1): this fraction of the report is printed
211 * A float (between 0 and 1): this fraction of the report is printed
212 (for example, use a limit of 0.4 to see the topmost 40% only).
212 (for example, use a limit of 0.4 to see the topmost 40% only).
213
213
214 You can combine several limits with repeated use of the option. For
214 You can combine several limits with repeated use of the option. For
215 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
215 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
216 information about class constructors.
216 information about class constructors.
217
217
218 -r
218 -r
219 return the pstats.Stats object generated by the profiling. This
219 return the pstats.Stats object generated by the profiling. This
220 object has all the information about the profile in it, and you can
220 object has all the information about the profile in it, and you can
221 later use it for further analysis or in other functions.
221 later use it for further analysis or in other functions.
222
222
223 -s <key>
223 -s <key>
224 sort profile by given key. You can provide more than one key
224 sort profile by given key. You can provide more than one key
225 by using the option several times: '-s key1 -s key2 -s key3...'. The
225 by using the option several times: '-s key1 -s key2 -s key3...'. The
226 default sorting key is 'time'.
226 default sorting key is 'time'.
227
227
228 The following is copied verbatim from the profile documentation
228 The following is copied verbatim from the profile documentation
229 referenced below:
229 referenced below:
230
230
231 When more than one key is provided, additional keys are used as
231 When more than one key is provided, additional keys are used as
232 secondary criteria when the there is equality in all keys selected
232 secondary criteria when the there is equality in all keys selected
233 before them.
233 before them.
234
234
235 Abbreviations can be used for any key names, as long as the
235 Abbreviations can be used for any key names, as long as the
236 abbreviation is unambiguous. The following are the keys currently
236 abbreviation is unambiguous. The following are the keys currently
237 defined:
237 defined:
238
238
239 ============ =====================
239 ============ =====================
240 Valid Arg Meaning
240 Valid Arg Meaning
241 ============ =====================
241 ============ =====================
242 "calls" call count
242 "calls" call count
243 "cumulative" cumulative time
243 "cumulative" cumulative time
244 "file" file name
244 "file" file name
245 "module" file name
245 "module" file name
246 "pcalls" primitive call count
246 "pcalls" primitive call count
247 "line" line number
247 "line" line number
248 "name" function name
248 "name" function name
249 "nfl" name/file/line
249 "nfl" name/file/line
250 "stdname" standard name
250 "stdname" standard name
251 "time" internal time
251 "time" internal time
252 ============ =====================
252 ============ =====================
253
253
254 Note that all sorts on statistics are in descending order (placing
254 Note that all sorts on statistics are in descending order (placing
255 most time consuming items first), where as name, file, and line number
255 most time consuming items first), where as name, file, and line number
256 searches are in ascending order (i.e., alphabetical). The subtle
256 searches are in ascending order (i.e., alphabetical). The subtle
257 distinction between "nfl" and "stdname" is that the standard name is a
257 distinction between "nfl" and "stdname" is that the standard name is a
258 sort of the name as printed, which means that the embedded line
258 sort of the name as printed, which means that the embedded line
259 numbers get compared in an odd way. For example, lines 3, 20, and 40
259 numbers get compared in an odd way. For example, lines 3, 20, and 40
260 would (if the file names were the same) appear in the string order
260 would (if the file names were the same) appear in the string order
261 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
261 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
262 line numbers. In fact, sort_stats("nfl") is the same as
262 line numbers. In fact, sort_stats("nfl") is the same as
263 sort_stats("name", "file", "line").
263 sort_stats("name", "file", "line").
264
264
265 -T <filename>
265 -T <filename>
266 save profile results as shown on screen to a text
266 save profile results as shown on screen to a text
267 file. The profile is still shown on screen.
267 file. The profile is still shown on screen.
268
268
269 -D <filename>
269 -D <filename>
270 save (via dump_stats) profile statistics to given
270 save (via dump_stats) profile statistics to given
271 filename. This data is in a format understood by the pstats module, and
271 filename. This data is in a format understood by the pstats module, and
272 is generated by a call to the dump_stats() method of profile
272 is generated by a call to the dump_stats() method of profile
273 objects. The profile is still shown on screen.
273 objects. The profile is still shown on screen.
274
274
275 -q
275 -q
276 suppress output to the pager. Best used with -T and/or -D above.
276 suppress output to the pager. Best used with -T and/or -D above.
277
277
278 If you want to run complete programs under the profiler's control, use
278 If you want to run complete programs under the profiler's control, use
279 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
279 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
280 contains profiler specific options as described here.
280 contains profiler specific options as described here.
281
281
282 You can read the complete documentation for the profile module with::
282 You can read the complete documentation for the profile module with::
283
283
284 In [1]: import profile; profile.help()
284 In [1]: import profile; profile.help()
285
285
286 .. versionchanged:: 7.3
286 .. versionchanged:: 7.3
287 User variables are no longer expanded,
287 User variables are no longer expanded,
288 the magic line is always left unmodified.
288 the magic line is always left unmodified.
289
289
290 """
290 """
291 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
291 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
292 list_all=True, posix=False)
292 list_all=True, posix=False)
293 if cell is not None:
293 if cell is not None:
294 arg_str += '\n' + cell
294 arg_str += '\n' + cell
295 arg_str = self.shell.transform_cell(arg_str)
295 arg_str = self.shell.transform_cell(arg_str)
296 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
296 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
297
297
298 def _run_with_profiler(self, code, opts, namespace):
298 def _run_with_profiler(self, code, opts, namespace):
299 """
299 """
300 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
300 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
301
301
302 Parameters
302 Parameters
303 ----------
303 ----------
304 code : str
304 code : str
305 Code to be executed.
305 Code to be executed.
306 opts : Struct
306 opts : Struct
307 Options parsed by `self.parse_options`.
307 Options parsed by `self.parse_options`.
308 namespace : dict
308 namespace : dict
309 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
309 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
310
310
311 """
311 """
312
312
313 # Fill default values for unspecified options:
313 # Fill default values for unspecified options:
314 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
314 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
315
315
316 prof = profile.Profile()
316 prof = profile.Profile()
317 try:
317 try:
318 prof = prof.runctx(code, namespace, namespace)
318 prof = prof.runctx(code, namespace, namespace)
319 sys_exit = ''
319 sys_exit = ''
320 except SystemExit:
320 except SystemExit:
321 sys_exit = """*** SystemExit exception caught in code being profiled."""
321 sys_exit = """*** SystemExit exception caught in code being profiled."""
322
322
323 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
323 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
324
324
325 lims = opts.l
325 lims = opts.l
326 if lims:
326 if lims:
327 lims = [] # rebuild lims with ints/floats/strings
327 lims = [] # rebuild lims with ints/floats/strings
328 for lim in opts.l:
328 for lim in opts.l:
329 try:
329 try:
330 lims.append(int(lim))
330 lims.append(int(lim))
331 except ValueError:
331 except ValueError:
332 try:
332 try:
333 lims.append(float(lim))
333 lims.append(float(lim))
334 except ValueError:
334 except ValueError:
335 lims.append(lim)
335 lims.append(lim)
336
336
337 # Trap output.
337 # Trap output.
338 stdout_trap = StringIO()
338 stdout_trap = StringIO()
339 stats_stream = stats.stream
339 stats_stream = stats.stream
340 try:
340 try:
341 stats.stream = stdout_trap
341 stats.stream = stdout_trap
342 stats.print_stats(*lims)
342 stats.print_stats(*lims)
343 finally:
343 finally:
344 stats.stream = stats_stream
344 stats.stream = stats_stream
345
345
346 output = stdout_trap.getvalue()
346 output = stdout_trap.getvalue()
347 output = output.rstrip()
347 output = output.rstrip()
348
348
349 if 'q' not in opts:
349 if 'q' not in opts:
350 page.page(output)
350 page.page(output)
351 print(sys_exit, end=' ')
351 print(sys_exit, end=' ')
352
352
353 dump_file = opts.D[0]
353 dump_file = opts.D[0]
354 text_file = opts.T[0]
354 text_file = opts.T[0]
355 if dump_file:
355 if dump_file:
356 prof.dump_stats(dump_file)
356 prof.dump_stats(dump_file)
357 print(
357 print(
358 f"\n*** Profile stats marshalled to file {repr(dump_file)}.{sys_exit}"
358 f"\n*** Profile stats marshalled to file {repr(dump_file)}.{sys_exit}"
359 )
359 )
360 if text_file:
360 if text_file:
361 pfile = Path(text_file)
361 pfile = Path(text_file)
362 pfile.touch(exist_ok=True)
362 pfile.touch(exist_ok=True)
363 pfile.write_text(output)
363 pfile.write_text(output)
364
364
365 print(
365 print(
366 f"\n*** Profile printout saved to text file {repr(text_file)}.{sys_exit}"
366 f"\n*** Profile printout saved to text file {repr(text_file)}.{sys_exit}"
367 )
367 )
368
368
369 if 'r' in opts:
369 if 'r' in opts:
370 return stats
370 return stats
371
371
372 return None
372 return None
373
373
374 @line_magic
374 @line_magic
375 def pdb(self, parameter_s=''):
375 def pdb(self, parameter_s=''):
376 """Control the automatic calling of the pdb interactive debugger.
376 """Control the automatic calling of the pdb interactive debugger.
377
377
378 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
378 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
379 argument it works as a toggle.
379 argument it works as a toggle.
380
380
381 When an exception is triggered, IPython can optionally call the
381 When an exception is triggered, IPython can optionally call the
382 interactive pdb debugger after the traceback printout. %pdb toggles
382 interactive pdb debugger after the traceback printout. %pdb toggles
383 this feature on and off.
383 this feature on and off.
384
384
385 The initial state of this feature is set in your configuration
385 The initial state of this feature is set in your configuration
386 file (the option is ``InteractiveShell.pdb``).
386 file (the option is ``InteractiveShell.pdb``).
387
387
388 If you want to just activate the debugger AFTER an exception has fired,
388 If you want to just activate the debugger AFTER an exception has fired,
389 without having to type '%pdb on' and rerunning your code, you can use
389 without having to type '%pdb on' and rerunning your code, you can use
390 the %debug magic."""
390 the %debug magic."""
391
391
392 par = parameter_s.strip().lower()
392 par = parameter_s.strip().lower()
393
393
394 if par:
394 if par:
395 try:
395 try:
396 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
396 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
397 except KeyError:
397 except KeyError:
398 print ('Incorrect argument. Use on/1, off/0, '
398 print ('Incorrect argument. Use on/1, off/0, '
399 'or nothing for a toggle.')
399 'or nothing for a toggle.')
400 return
400 return
401 else:
401 else:
402 # toggle
402 # toggle
403 new_pdb = not self.shell.call_pdb
403 new_pdb = not self.shell.call_pdb
404
404
405 # set on the shell
405 # set on the shell
406 self.shell.call_pdb = new_pdb
406 self.shell.call_pdb = new_pdb
407 print('Automatic pdb calling has been turned',on_off(new_pdb))
407 print('Automatic pdb calling has been turned',on_off(new_pdb))
408
408
409 @magic_arguments.magic_arguments()
409 @magic_arguments.magic_arguments()
410 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
410 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
411 help="""
411 help="""
412 Set break point at LINE in FILE.
412 Set break point at LINE in FILE.
413 """
413 """
414 )
414 )
415 @magic_arguments.argument('statement', nargs='*',
415 @magic_arguments.argument('statement', nargs='*',
416 help="""
416 help="""
417 Code to run in debugger.
417 Code to run in debugger.
418 You can omit this in cell magic mode.
418 You can omit this in cell magic mode.
419 """
419 """
420 )
420 )
421 @no_var_expand
421 @no_var_expand
422 @line_cell_magic
422 @line_cell_magic
423 def debug(self, line='', cell=None):
423 def debug(self, line='', cell=None):
424 """Activate the interactive debugger.
424 """Activate the interactive debugger.
425
425
426 This magic command support two ways of activating debugger.
426 This magic command support two ways of activating debugger.
427 One is to activate debugger before executing code. This way, you
427 One is to activate debugger before executing code. This way, you
428 can set a break point, to step through the code from the point.
428 can set a break point, to step through the code from the point.
429 You can use this mode by giving statements to execute and optionally
429 You can use this mode by giving statements to execute and optionally
430 a breakpoint.
430 a breakpoint.
431
431
432 The other one is to activate debugger in post-mortem mode. You can
432 The other one is to activate debugger in post-mortem mode. You can
433 activate this mode simply running %debug without any argument.
433 activate this mode simply running %debug without any argument.
434 If an exception has just occurred, this lets you inspect its stack
434 If an exception has just occurred, this lets you inspect its stack
435 frames interactively. Note that this will always work only on the last
435 frames interactively. Note that this will always work only on the last
436 traceback that occurred, so you must call this quickly after an
436 traceback that occurred, so you must call this quickly after an
437 exception that you wish to inspect has fired, because if another one
437 exception that you wish to inspect has fired, because if another one
438 occurs, it clobbers the previous one.
438 occurs, it clobbers the previous one.
439
439
440 If you want IPython to automatically do this on every exception, see
440 If you want IPython to automatically do this on every exception, see
441 the %pdb magic for more details.
441 the %pdb magic for more details.
442
442
443 .. versionchanged:: 7.3
443 .. versionchanged:: 7.3
444 When running code, user variables are no longer expanded,
444 When running code, user variables are no longer expanded,
445 the magic line is always left unmodified.
445 the magic line is always left unmodified.
446
446
447 """
447 """
448 args = magic_arguments.parse_argstring(self.debug, line)
448 args = magic_arguments.parse_argstring(self.debug, line)
449
449
450 if not (args.breakpoint or args.statement or cell):
450 if not (args.breakpoint or args.statement or cell):
451 self._debug_post_mortem()
451 self._debug_post_mortem()
452 elif not (args.breakpoint or cell):
452 elif not (args.breakpoint or cell):
453 # If there is no breakpoints, the line is just code to execute
453 # If there is no breakpoints, the line is just code to execute
454 self._debug_exec(line, None)
454 self._debug_exec(line, None)
455 else:
455 else:
456 # Here we try to reconstruct the code from the output of
456 # Here we try to reconstruct the code from the output of
457 # parse_argstring. This might not work if the code has spaces
457 # parse_argstring. This might not work if the code has spaces
458 # For example this fails for `print("a b")`
458 # For example this fails for `print("a b")`
459 code = "\n".join(args.statement)
459 code = "\n".join(args.statement)
460 if cell:
460 if cell:
461 code += "\n" + cell
461 code += "\n" + cell
462 self._debug_exec(code, args.breakpoint)
462 self._debug_exec(code, args.breakpoint)
463
463
464 def _debug_post_mortem(self):
464 def _debug_post_mortem(self):
465 self.shell.debugger(force=True)
465 self.shell.debugger(force=True)
466
466
467 def _debug_exec(self, code, breakpoint):
467 def _debug_exec(self, code, breakpoint):
468 if breakpoint:
468 if breakpoint:
469 (filename, bp_line) = breakpoint.rsplit(':', 1)
469 (filename, bp_line) = breakpoint.rsplit(':', 1)
470 bp_line = int(bp_line)
470 bp_line = int(bp_line)
471 else:
471 else:
472 (filename, bp_line) = (None, None)
472 (filename, bp_line) = (None, None)
473 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
473 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
474
474
475 @line_magic
475 @line_magic
476 def tb(self, s):
476 def tb(self, s):
477 """Print the last traceback.
477 """Print the last traceback.
478
478
479 Optionally, specify an exception reporting mode, tuning the
479 Optionally, specify an exception reporting mode, tuning the
480 verbosity of the traceback. By default the currently-active exception
480 verbosity of the traceback. By default the currently-active exception
481 mode is used. See %xmode for changing exception reporting modes.
481 mode is used. See %xmode for changing exception reporting modes.
482
482
483 Valid modes: Plain, Context, Verbose, and Minimal.
483 Valid modes: Plain, Context, Verbose, and Minimal.
484 """
484 """
485 interactive_tb = self.shell.InteractiveTB
485 interactive_tb = self.shell.InteractiveTB
486 if s:
486 if s:
487 # Switch exception reporting mode for this one call.
487 # Switch exception reporting mode for this one call.
488 # Ensure it is switched back.
488 # Ensure it is switched back.
489 def xmode_switch_err(name):
489 def xmode_switch_err(name):
490 warn('Error changing %s exception modes.\n%s' %
490 warn('Error changing %s exception modes.\n%s' %
491 (name,sys.exc_info()[1]))
491 (name,sys.exc_info()[1]))
492
492
493 new_mode = s.strip().capitalize()
493 new_mode = s.strip().capitalize()
494 original_mode = interactive_tb.mode
494 original_mode = interactive_tb.mode
495 try:
495 try:
496 try:
496 try:
497 interactive_tb.set_mode(mode=new_mode)
497 interactive_tb.set_mode(mode=new_mode)
498 except Exception:
498 except Exception:
499 xmode_switch_err('user')
499 xmode_switch_err('user')
500 else:
500 else:
501 self.shell.showtraceback()
501 self.shell.showtraceback()
502 finally:
502 finally:
503 interactive_tb.set_mode(mode=original_mode)
503 interactive_tb.set_mode(mode=original_mode)
504 else:
504 else:
505 self.shell.showtraceback()
505 self.shell.showtraceback()
506
506
507 @skip_doctest
507 @skip_doctest
508 @line_magic
508 @line_magic
509 def run(self, parameter_s='', runner=None,
509 def run(self, parameter_s='', runner=None,
510 file_finder=get_py_filename):
510 file_finder=get_py_filename):
511 """Run the named file inside IPython as a program.
511 """Run the named file inside IPython as a program.
512
512
513 Usage::
513 Usage::
514
514
515 %run [-n -i -e -G]
515 %run [-n -i -e -G]
516 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
516 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
517 ( -m mod | filename ) [args]
517 ( -m mod | filename ) [args]
518
518
519 The filename argument should be either a pure Python script (with
519 The filename argument should be either a pure Python script (with
520 extension ``.py``), or a file with custom IPython syntax (such as
520 extension ``.py``), or a file with custom IPython syntax (such as
521 magics). If the latter, the file can be either a script with ``.ipy``
521 magics). If the latter, the file can be either a script with ``.ipy``
522 extension, or a Jupyter notebook with ``.ipynb`` extension. When running
522 extension, or a Jupyter notebook with ``.ipynb`` extension. When running
523 a Jupyter notebook, the output from print statements and other
523 a Jupyter notebook, the output from print statements and other
524 displayed objects will appear in the terminal (even matplotlib figures
524 displayed objects will appear in the terminal (even matplotlib figures
525 will open, if a terminal-compliant backend is being used). Note that,
525 will open, if a terminal-compliant backend is being used). Note that,
526 at the system command line, the ``jupyter run`` command offers similar
526 at the system command line, the ``jupyter run`` command offers similar
527 functionality for executing notebooks (albeit currently with some
527 functionality for executing notebooks (albeit currently with some
528 differences in supported options).
528 differences in supported options).
529
529
530 Parameters after the filename are passed as command-line arguments to
530 Parameters after the filename are passed as command-line arguments to
531 the program (put in sys.argv). Then, control returns to IPython's
531 the program (put in sys.argv). Then, control returns to IPython's
532 prompt.
532 prompt.
533
533
534 This is similar to running at a system prompt ``python file args``,
534 This is similar to running at a system prompt ``python file args``,
535 but with the advantage of giving you IPython's tracebacks, and of
535 but with the advantage of giving you IPython's tracebacks, and of
536 loading all variables into your interactive namespace for further use
536 loading all variables into your interactive namespace for further use
537 (unless -p is used, see below).
537 (unless -p is used, see below).
538
538
539 The file is executed in a namespace initially consisting only of
539 The file is executed in a namespace initially consisting only of
540 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
540 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
541 sees its environment as if it were being run as a stand-alone program
541 sees its environment as if it were being run as a stand-alone program
542 (except for sharing global objects such as previously imported
542 (except for sharing global objects such as previously imported
543 modules). But after execution, the IPython interactive namespace gets
543 modules). But after execution, the IPython interactive namespace gets
544 updated with all variables defined in the program (except for __name__
544 updated with all variables defined in the program (except for __name__
545 and sys.argv). This allows for very convenient loading of code for
545 and sys.argv). This allows for very convenient loading of code for
546 interactive work, while giving each program a 'clean sheet' to run in.
546 interactive work, while giving each program a 'clean sheet' to run in.
547
547
548 Arguments are expanded using shell-like glob match. Patterns
548 Arguments are expanded using shell-like glob match. Patterns
549 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
549 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
550 tilde '~' will be expanded into user's home directory. Unlike
550 tilde '~' will be expanded into user's home directory. Unlike
551 real shells, quotation does not suppress expansions. Use
551 real shells, quotation does not suppress expansions. Use
552 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
552 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
553 To completely disable these expansions, you can use -G flag.
553 To completely disable these expansions, you can use -G flag.
554
554
555 On Windows systems, the use of single quotes `'` when specifying
555 On Windows systems, the use of single quotes `'` when specifying
556 a file is not supported. Use double quotes `"`.
556 a file is not supported. Use double quotes `"`.
557
557
558 Options:
558 Options:
559
559
560 -n
560 -n
561 __name__ is NOT set to '__main__', but to the running file's name
561 __name__ is NOT set to '__main__', but to the running file's name
562 without extension (as python does under import). This allows running
562 without extension (as python does under import). This allows running
563 scripts and reloading the definitions in them without calling code
563 scripts and reloading the definitions in them without calling code
564 protected by an ``if __name__ == "__main__"`` clause.
564 protected by an ``if __name__ == "__main__"`` clause.
565
565
566 -i
566 -i
567 run the file in IPython's namespace instead of an empty one. This
567 run the file in IPython's namespace instead of an empty one. This
568 is useful if you are experimenting with code written in a text editor
568 is useful if you are experimenting with code written in a text editor
569 which depends on variables defined interactively.
569 which depends on variables defined interactively.
570
570
571 -e
571 -e
572 ignore sys.exit() calls or SystemExit exceptions in the script
572 ignore sys.exit() calls or SystemExit exceptions in the script
573 being run. This is particularly useful if IPython is being used to
573 being run. This is particularly useful if IPython is being used to
574 run unittests, which always exit with a sys.exit() call. In such
574 run unittests, which always exit with a sys.exit() call. In such
575 cases you are interested in the output of the test results, not in
575 cases you are interested in the output of the test results, not in
576 seeing a traceback of the unittest module.
576 seeing a traceback of the unittest module.
577
577
578 -t
578 -t
579 print timing information at the end of the run. IPython will give
579 print timing information at the end of the run. IPython will give
580 you an estimated CPU time consumption for your script, which under
580 you an estimated CPU time consumption for your script, which under
581 Unix uses the resource module to avoid the wraparound problems of
581 Unix uses the resource module to avoid the wraparound problems of
582 time.clock(). Under Unix, an estimate of time spent on system tasks
582 time.clock(). Under Unix, an estimate of time spent on system tasks
583 is also given (for Windows platforms this is reported as 0.0).
583 is also given (for Windows platforms this is reported as 0.0).
584
584
585 If -t is given, an additional ``-N<N>`` option can be given, where <N>
585 If -t is given, an additional ``-N<N>`` option can be given, where <N>
586 must be an integer indicating how many times you want the script to
586 must be an integer indicating how many times you want the script to
587 run. The final timing report will include total and per run results.
587 run. The final timing report will include total and per run results.
588
588
589 For example (testing the script uniq_stable.py)::
589 For example (testing the script uniq_stable.py)::
590
590
591 In [1]: run -t uniq_stable
591 In [1]: run -t uniq_stable
592
592
593 IPython CPU timings (estimated):
593 IPython CPU timings (estimated):
594 User : 0.19597 s.
594 User : 0.19597 s.
595 System: 0.0 s.
595 System: 0.0 s.
596
596
597 In [2]: run -t -N5 uniq_stable
597 In [2]: run -t -N5 uniq_stable
598
598
599 IPython CPU timings (estimated):
599 IPython CPU timings (estimated):
600 Total runs performed: 5
600 Total runs performed: 5
601 Times : Total Per run
601 Times : Total Per run
602 User : 0.910862 s, 0.1821724 s.
602 User : 0.910862 s, 0.1821724 s.
603 System: 0.0 s, 0.0 s.
603 System: 0.0 s, 0.0 s.
604
604
605 -d
605 -d
606 run your program under the control of pdb, the Python debugger.
606 run your program under the control of pdb, the Python debugger.
607 This allows you to execute your program step by step, watch variables,
607 This allows you to execute your program step by step, watch variables,
608 etc. Internally, what IPython does is similar to calling::
608 etc. Internally, what IPython does is similar to calling::
609
609
610 pdb.run('execfile("YOURFILENAME")')
610 pdb.run('execfile("YOURFILENAME")')
611
611
612 with a breakpoint set on line 1 of your file. You can change the line
612 with a breakpoint set on line 1 of your file. You can change the line
613 number for this automatic breakpoint to be <N> by using the -bN option
613 number for this automatic breakpoint to be <N> by using the -bN option
614 (where N must be an integer). For example::
614 (where N must be an integer). For example::
615
615
616 %run -d -b40 myscript
616 %run -d -b40 myscript
617
617
618 will set the first breakpoint at line 40 in myscript.py. Note that
618 will set the first breakpoint at line 40 in myscript.py. Note that
619 the first breakpoint must be set on a line which actually does
619 the first breakpoint must be set on a line which actually does
620 something (not a comment or docstring) for it to stop execution.
620 something (not a comment or docstring) for it to stop execution.
621
621
622 Or you can specify a breakpoint in a different file::
622 Or you can specify a breakpoint in a different file::
623
623
624 %run -d -b myotherfile.py:20 myscript
624 %run -d -b myotherfile.py:20 myscript
625
625
626 When the pdb debugger starts, you will see a (Pdb) prompt. You must
626 When the pdb debugger starts, you will see a (Pdb) prompt. You must
627 first enter 'c' (without quotes) to start execution up to the first
627 first enter 'c' (without quotes) to start execution up to the first
628 breakpoint.
628 breakpoint.
629
629
630 Entering 'help' gives information about the use of the debugger. You
630 Entering 'help' gives information about the use of the debugger. You
631 can easily see pdb's full documentation with "import pdb;pdb.help()"
631 can easily see pdb's full documentation with "import pdb;pdb.help()"
632 at a prompt.
632 at a prompt.
633
633
634 -p
634 -p
635 run program under the control of the Python profiler module (which
635 run program under the control of the Python profiler module (which
636 prints a detailed report of execution times, function calls, etc).
636 prints a detailed report of execution times, function calls, etc).
637
637
638 You can pass other options after -p which affect the behavior of the
638 You can pass other options after -p which affect the behavior of the
639 profiler itself. See the docs for %prun for details.
639 profiler itself. See the docs for %prun for details.
640
640
641 In this mode, the program's variables do NOT propagate back to the
641 In this mode, the program's variables do NOT propagate back to the
642 IPython interactive namespace (because they remain in the namespace
642 IPython interactive namespace (because they remain in the namespace
643 where the profiler executes them).
643 where the profiler executes them).
644
644
645 Internally this triggers a call to %prun, see its documentation for
645 Internally this triggers a call to %prun, see its documentation for
646 details on the options available specifically for profiling.
646 details on the options available specifically for profiling.
647
647
648 There is one special usage for which the text above doesn't apply:
648 There is one special usage for which the text above doesn't apply:
649 if the filename ends with .ipy[nb], the file is run as ipython script,
649 if the filename ends with .ipy[nb], the file is run as ipython script,
650 just as if the commands were written on IPython prompt.
650 just as if the commands were written on IPython prompt.
651
651
652 -m
652 -m
653 specify module name to load instead of script path. Similar to
653 specify module name to load instead of script path. Similar to
654 the -m option for the python interpreter. Use this option last if you
654 the -m option for the python interpreter. Use this option last if you
655 want to combine with other %run options. Unlike the python interpreter
655 want to combine with other %run options. Unlike the python interpreter
656 only source modules are allowed no .pyc or .pyo files.
656 only source modules are allowed no .pyc or .pyo files.
657 For example::
657 For example::
658
658
659 %run -m example
659 %run -m example
660
660
661 will run the example module.
661 will run the example module.
662
662
663 -G
663 -G
664 disable shell-like glob expansion of arguments.
664 disable shell-like glob expansion of arguments.
665
665
666 """
666 """
667
667
668 # Logic to handle issue #3664
668 # Logic to handle issue #3664
669 # Add '--' after '-m <module_name>' to ignore additional args passed to a module.
669 # Add '--' after '-m <module_name>' to ignore additional args passed to a module.
670 if '-m' in parameter_s and '--' not in parameter_s:
670 if '-m' in parameter_s and '--' not in parameter_s:
671 argv = shlex.split(parameter_s, posix=(os.name == 'posix'))
671 argv = shlex.split(parameter_s, posix=(os.name == 'posix'))
672 for idx, arg in enumerate(argv):
672 for idx, arg in enumerate(argv):
673 if arg and arg.startswith('-') and arg != '-':
673 if arg and arg.startswith('-') and arg != '-':
674 if arg == '-m':
674 if arg == '-m':
675 argv.insert(idx + 2, '--')
675 argv.insert(idx + 2, '--')
676 break
676 break
677 else:
677 else:
678 # Positional arg, break
678 # Positional arg, break
679 break
679 break
680 parameter_s = ' '.join(shlex.quote(arg) for arg in argv)
680 parameter_s = ' '.join(shlex.quote(arg) for arg in argv)
681
681
682 # get arguments and set sys.argv for program to be run.
682 # get arguments and set sys.argv for program to be run.
683 opts, arg_lst = self.parse_options(parameter_s,
683 opts, arg_lst = self.parse_options(parameter_s,
684 'nidtN:b:pD:l:rs:T:em:G',
684 'nidtN:b:pD:l:rs:T:em:G',
685 mode='list', list_all=1)
685 mode='list', list_all=1)
686 if "m" in opts:
686 if "m" in opts:
687 modulename = opts["m"][0]
687 modulename = opts["m"][0]
688 modpath = find_mod(modulename)
688 modpath = find_mod(modulename)
689 if modpath is None:
689 if modpath is None:
690 msg = '%r is not a valid modulename on sys.path'%modulename
690 msg = '%r is not a valid modulename on sys.path'%modulename
691 raise Exception(msg)
691 raise Exception(msg)
692 arg_lst = [modpath] + arg_lst
692 arg_lst = [modpath] + arg_lst
693 try:
693 try:
694 fpath = None # initialize to make sure fpath is in scope later
694 fpath = None # initialize to make sure fpath is in scope later
695 fpath = arg_lst[0]
695 fpath = arg_lst[0]
696 filename = file_finder(fpath)
696 filename = file_finder(fpath)
697 except IndexError as e:
697 except IndexError as e:
698 msg = 'you must provide at least a filename.'
698 msg = 'you must provide at least a filename.'
699 raise Exception(msg) from e
699 raise Exception(msg) from e
700 except IOError as e:
700 except IOError as e:
701 try:
701 try:
702 msg = str(e)
702 msg = str(e)
703 except UnicodeError:
703 except UnicodeError:
704 msg = e.message
704 msg = e.message
705 if os.name == 'nt' and re.match(r"^'.*'$",fpath):
705 if os.name == 'nt' and re.match(r"^'.*'$",fpath):
706 warn('For Windows, use double quotes to wrap a filename: %run "mypath\\myfile.py"')
706 warn('For Windows, use double quotes to wrap a filename: %run "mypath\\myfile.py"')
707 raise Exception(msg) from e
707 raise Exception(msg) from e
708 except TypeError:
708 except TypeError:
709 if fpath in sys.meta_path:
709 if fpath in sys.meta_path:
710 filename = ""
710 filename = ""
711 else:
711 else:
712 raise
712 raise
713
713
714 if filename.lower().endswith(('.ipy', '.ipynb')):
714 if filename.lower().endswith(('.ipy', '.ipynb')):
715 with preserve_keys(self.shell.user_ns, '__file__'):
715 with preserve_keys(self.shell.user_ns, '__file__'):
716 self.shell.user_ns['__file__'] = filename
716 self.shell.user_ns['__file__'] = filename
717 self.shell.safe_execfile_ipy(filename, raise_exceptions=True)
717 self.shell.safe_execfile_ipy(filename, raise_exceptions=True)
718 return
718 return
719
719
720 # Control the response to exit() calls made by the script being run
720 # Control the response to exit() calls made by the script being run
721 exit_ignore = 'e' in opts
721 exit_ignore = 'e' in opts
722
722
723 # Make sure that the running script gets a proper sys.argv as if it
723 # Make sure that the running script gets a proper sys.argv as if it
724 # were run from a system shell.
724 # were run from a system shell.
725 save_argv = sys.argv # save it for later restoring
725 save_argv = sys.argv # save it for later restoring
726
726
727 if 'G' in opts:
727 if 'G' in opts:
728 args = arg_lst[1:]
728 args = arg_lst[1:]
729 else:
729 else:
730 # tilde and glob expansion
730 # tilde and glob expansion
731 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
731 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
732
732
733 sys.argv = [filename] + args # put in the proper filename
733 sys.argv = [filename] + args # put in the proper filename
734
734
735 if 'n' in opts:
735 if 'n' in opts:
736 name = Path(filename).stem
736 name = Path(filename).stem
737 else:
737 else:
738 name = '__main__'
738 name = '__main__'
739
739
740 if 'i' in opts:
740 if 'i' in opts:
741 # Run in user's interactive namespace
741 # Run in user's interactive namespace
742 prog_ns = self.shell.user_ns
742 prog_ns = self.shell.user_ns
743 __name__save = self.shell.user_ns['__name__']
743 __name__save = self.shell.user_ns['__name__']
744 prog_ns['__name__'] = name
744 prog_ns['__name__'] = name
745 main_mod = self.shell.user_module
745 main_mod = self.shell.user_module
746
746
747 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
747 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
748 # set the __file__ global in the script's namespace
748 # set the __file__ global in the script's namespace
749 # TK: Is this necessary in interactive mode?
749 # TK: Is this necessary in interactive mode?
750 prog_ns['__file__'] = filename
750 prog_ns['__file__'] = filename
751 else:
751 else:
752 # Run in a fresh, empty namespace
752 # Run in a fresh, empty namespace
753
753
754 # The shell MUST hold a reference to prog_ns so after %run
754 # The shell MUST hold a reference to prog_ns so after %run
755 # exits, the python deletion mechanism doesn't zero it out
755 # exits, the python deletion mechanism doesn't zero it out
756 # (leaving dangling references). See interactiveshell for details
756 # (leaving dangling references). See interactiveshell for details
757 main_mod = self.shell.new_main_mod(filename, name)
757 main_mod = self.shell.new_main_mod(filename, name)
758 prog_ns = main_mod.__dict__
758 prog_ns = main_mod.__dict__
759
759
760 # pickle fix. See interactiveshell for an explanation. But we need to
760 # pickle fix. See interactiveshell for an explanation. But we need to
761 # make sure that, if we overwrite __main__, we replace it at the end
761 # make sure that, if we overwrite __main__, we replace it at the end
762 main_mod_name = prog_ns['__name__']
762 main_mod_name = prog_ns['__name__']
763
763
764 if main_mod_name == '__main__':
764 if main_mod_name == '__main__':
765 restore_main = sys.modules['__main__']
765 restore_main = sys.modules['__main__']
766 else:
766 else:
767 restore_main = False
767 restore_main = False
768
768
769 # This needs to be undone at the end to prevent holding references to
769 # This needs to be undone at the end to prevent holding references to
770 # every single object ever created.
770 # every single object ever created.
771 sys.modules[main_mod_name] = main_mod
771 sys.modules[main_mod_name] = main_mod
772
772
773 if 'p' in opts or 'd' in opts:
773 if 'p' in opts or 'd' in opts:
774 if 'm' in opts:
774 if 'm' in opts:
775 code = 'run_module(modulename, prog_ns)'
775 code = 'run_module(modulename, prog_ns)'
776 code_ns = {
776 code_ns = {
777 'run_module': self.shell.safe_run_module,
777 'run_module': self.shell.safe_run_module,
778 'prog_ns': prog_ns,
778 'prog_ns': prog_ns,
779 'modulename': modulename,
779 'modulename': modulename,
780 }
780 }
781 else:
781 else:
782 if 'd' in opts:
782 if 'd' in opts:
783 # allow exceptions to raise in debug mode
783 # allow exceptions to raise in debug mode
784 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
784 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
785 else:
785 else:
786 code = 'execfile(filename, prog_ns)'
786 code = 'execfile(filename, prog_ns)'
787 code_ns = {
787 code_ns = {
788 'execfile': self.shell.safe_execfile,
788 'execfile': self.shell.safe_execfile,
789 'prog_ns': prog_ns,
789 'prog_ns': prog_ns,
790 'filename': get_py_filename(filename),
790 'filename': get_py_filename(filename),
791 }
791 }
792
792
793 try:
793 try:
794 stats = None
794 stats = None
795 if 'p' in opts:
795 if 'p' in opts:
796 stats = self._run_with_profiler(code, opts, code_ns)
796 stats = self._run_with_profiler(code, opts, code_ns)
797 else:
797 else:
798 if 'd' in opts:
798 if 'd' in opts:
799 bp_file, bp_line = parse_breakpoint(
799 bp_file, bp_line = parse_breakpoint(
800 opts.get('b', ['1'])[0], filename)
800 opts.get('b', ['1'])[0], filename)
801 self._run_with_debugger(
801 self._run_with_debugger(
802 code, code_ns, filename, bp_line, bp_file)
802 code, code_ns, filename, bp_line, bp_file)
803 else:
803 else:
804 if 'm' in opts:
804 if 'm' in opts:
805 def run():
805 def run():
806 self.shell.safe_run_module(modulename, prog_ns)
806 self.shell.safe_run_module(modulename, prog_ns)
807 else:
807 else:
808 if runner is None:
808 if runner is None:
809 runner = self.default_runner
809 runner = self.default_runner
810 if runner is None:
810 if runner is None:
811 runner = self.shell.safe_execfile
811 runner = self.shell.safe_execfile
812
812
813 def run():
813 def run():
814 runner(filename, prog_ns, prog_ns,
814 runner(filename, prog_ns, prog_ns,
815 exit_ignore=exit_ignore)
815 exit_ignore=exit_ignore)
816
816
817 if 't' in opts:
817 if 't' in opts:
818 # timed execution
818 # timed execution
819 try:
819 try:
820 nruns = int(opts['N'][0])
820 nruns = int(opts['N'][0])
821 if nruns < 1:
821 if nruns < 1:
822 error('Number of runs must be >=1')
822 error('Number of runs must be >=1')
823 return
823 return
824 except (KeyError):
824 except (KeyError):
825 nruns = 1
825 nruns = 1
826 self._run_with_timing(run, nruns)
826 self._run_with_timing(run, nruns)
827 else:
827 else:
828 # regular execution
828 # regular execution
829 run()
829 run()
830
830
831 if 'i' in opts:
831 if 'i' in opts:
832 self.shell.user_ns['__name__'] = __name__save
832 self.shell.user_ns['__name__'] = __name__save
833 else:
833 else:
834 # update IPython interactive namespace
834 # update IPython interactive namespace
835
835
836 # Some forms of read errors on the file may mean the
836 # Some forms of read errors on the file may mean the
837 # __name__ key was never set; using pop we don't have to
837 # __name__ key was never set; using pop we don't have to
838 # worry about a possible KeyError.
838 # worry about a possible KeyError.
839 prog_ns.pop('__name__', None)
839 prog_ns.pop('__name__', None)
840
840
841 with preserve_keys(self.shell.user_ns, '__file__'):
841 with preserve_keys(self.shell.user_ns, '__file__'):
842 self.shell.user_ns.update(prog_ns)
842 self.shell.user_ns.update(prog_ns)
843 finally:
843 finally:
844 # It's a bit of a mystery why, but __builtins__ can change from
844 # It's a bit of a mystery why, but __builtins__ can change from
845 # being a module to becoming a dict missing some key data after
845 # being a module to becoming a dict missing some key data after
846 # %run. As best I can see, this is NOT something IPython is doing
846 # %run. As best I can see, this is NOT something IPython is doing
847 # at all, and similar problems have been reported before:
847 # at all, and similar problems have been reported before:
848 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
848 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
849 # Since this seems to be done by the interpreter itself, the best
849 # Since this seems to be done by the interpreter itself, the best
850 # we can do is to at least restore __builtins__ for the user on
850 # we can do is to at least restore __builtins__ for the user on
851 # exit.
851 # exit.
852 self.shell.user_ns['__builtins__'] = builtin_mod
852 self.shell.user_ns['__builtins__'] = builtin_mod
853
853
854 # Ensure key global structures are restored
854 # Ensure key global structures are restored
855 sys.argv = save_argv
855 sys.argv = save_argv
856 if restore_main:
856 if restore_main:
857 sys.modules['__main__'] = restore_main
857 sys.modules['__main__'] = restore_main
858 if '__mp_main__' in sys.modules:
858 if '__mp_main__' in sys.modules:
859 sys.modules['__mp_main__'] = restore_main
859 sys.modules['__mp_main__'] = restore_main
860 else:
860 else:
861 # Remove from sys.modules the reference to main_mod we'd
861 # Remove from sys.modules the reference to main_mod we'd
862 # added. Otherwise it will trap references to objects
862 # added. Otherwise it will trap references to objects
863 # contained therein.
863 # contained therein.
864 del sys.modules[main_mod_name]
864 del sys.modules[main_mod_name]
865
865
866 return stats
866 return stats
867
867
868 def _run_with_debugger(self, code, code_ns, filename=None,
868 def _run_with_debugger(self, code, code_ns, filename=None,
869 bp_line=None, bp_file=None):
869 bp_line=None, bp_file=None):
870 """
870 """
871 Run `code` in debugger with a break point.
871 Run `code` in debugger with a break point.
872
872
873 Parameters
873 Parameters
874 ----------
874 ----------
875 code : str
875 code : str
876 Code to execute.
876 Code to execute.
877 code_ns : dict
877 code_ns : dict
878 A namespace in which `code` is executed.
878 A namespace in which `code` is executed.
879 filename : str
879 filename : str
880 `code` is ran as if it is in `filename`.
880 `code` is ran as if it is in `filename`.
881 bp_line : int, optional
881 bp_line : int, optional
882 Line number of the break point.
882 Line number of the break point.
883 bp_file : str, optional
883 bp_file : str, optional
884 Path to the file in which break point is specified.
884 Path to the file in which break point is specified.
885 `filename` is used if not given.
885 `filename` is used if not given.
886
886
887 Raises
887 Raises
888 ------
888 ------
889 UsageError
889 UsageError
890 If the break point given by `bp_line` is not valid.
890 If the break point given by `bp_line` is not valid.
891
891
892 """
892 """
893 deb = self.shell.InteractiveTB.pdb
893 deb = self.shell.InteractiveTB.pdb
894 if not deb:
894 if not deb:
895 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
895 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
896 deb = self.shell.InteractiveTB.pdb
896 deb = self.shell.InteractiveTB.pdb
897
897
898 # deb.checkline() fails if deb.curframe exists but is None; it can
898 # deb.checkline() fails if deb.curframe exists but is None; it can
899 # handle it not existing. https://github.com/ipython/ipython/issues/10028
899 # handle it not existing. https://github.com/ipython/ipython/issues/10028
900 if hasattr(deb, 'curframe'):
900 if hasattr(deb, 'curframe'):
901 del deb.curframe
901 del deb.curframe
902
902
903 # reset Breakpoint state, which is moronically kept
903 # reset Breakpoint state, which is moronically kept
904 # in a class
904 # in a class
905 bdb.Breakpoint.next = 1
905 bdb.Breakpoint.next = 1
906 bdb.Breakpoint.bplist = {}
906 bdb.Breakpoint.bplist = {}
907 bdb.Breakpoint.bpbynumber = [None]
907 bdb.Breakpoint.bpbynumber = [None]
908 deb.clear_all_breaks()
908 deb.clear_all_breaks()
909 if bp_line is not None:
909 if bp_line is not None:
910 # Set an initial breakpoint to stop execution
910 # Set an initial breakpoint to stop execution
911 maxtries = 10
911 maxtries = 10
912 bp_file = bp_file or filename
912 bp_file = bp_file or filename
913 checkline = deb.checkline(bp_file, bp_line)
913 checkline = deb.checkline(bp_file, bp_line)
914 if not checkline:
914 if not checkline:
915 for bp in range(bp_line + 1, bp_line + maxtries + 1):
915 for bp in range(bp_line + 1, bp_line + maxtries + 1):
916 if deb.checkline(bp_file, bp):
916 if deb.checkline(bp_file, bp):
917 break
917 break
918 else:
918 else:
919 msg = ("\nI failed to find a valid line to set "
919 msg = ("\nI failed to find a valid line to set "
920 "a breakpoint\n"
920 "a breakpoint\n"
921 "after trying up to line: %s.\n"
921 "after trying up to line: %s.\n"
922 "Please set a valid breakpoint manually "
922 "Please set a valid breakpoint manually "
923 "with the -b option." % bp)
923 "with the -b option." % bp)
924 raise UsageError(msg)
924 raise UsageError(msg)
925 # if we find a good linenumber, set the breakpoint
925 # if we find a good linenumber, set the breakpoint
926 deb.do_break('%s:%s' % (bp_file, bp_line))
926 deb.do_break('%s:%s' % (bp_file, bp_line))
927
927
928 if filename:
928 if filename:
929 # Mimic Pdb._runscript(...)
929 # Mimic Pdb._runscript(...)
930 deb._wait_for_mainpyfile = True
930 deb._wait_for_mainpyfile = True
931 deb.mainpyfile = deb.canonic(filename)
931 deb.mainpyfile = deb.canonic(filename)
932
932
933 # Start file run
933 # Start file run
934 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
934 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
935 try:
935 try:
936 if filename:
936 if filename:
937 # save filename so it can be used by methods on the deb object
937 # save filename so it can be used by methods on the deb object
938 deb._exec_filename = filename
938 deb._exec_filename = filename
939 while True:
939 while True:
940 try:
940 try:
941 trace = sys.gettrace()
941 trace = sys.gettrace()
942 deb.run(code, code_ns)
942 deb.run(code, code_ns)
943 except Restart:
943 except Restart:
944 print("Restarting")
944 print("Restarting")
945 if filename:
945 if filename:
946 deb._wait_for_mainpyfile = True
946 deb._wait_for_mainpyfile = True
947 deb.mainpyfile = deb.canonic(filename)
947 deb.mainpyfile = deb.canonic(filename)
948 continue
948 continue
949 else:
949 else:
950 break
950 break
951 finally:
951 finally:
952 sys.settrace(trace)
952 sys.settrace(trace)
953
953
954
954
955 except:
955 except:
956 etype, value, tb = sys.exc_info()
956 etype, value, tb = sys.exc_info()
957 # Skip three frames in the traceback: the %run one,
957 # Skip three frames in the traceback: the %run one,
958 # one inside bdb.py, and the command-line typed by the
958 # one inside bdb.py, and the command-line typed by the
959 # user (run by exec in pdb itself).
959 # user (run by exec in pdb itself).
960 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
960 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
961
961
962 @staticmethod
962 @staticmethod
963 def _run_with_timing(run, nruns):
963 def _run_with_timing(run, nruns):
964 """
964 """
965 Run function `run` and print timing information.
965 Run function `run` and print timing information.
966
966
967 Parameters
967 Parameters
968 ----------
968 ----------
969 run : callable
969 run : callable
970 Any callable object which takes no argument.
970 Any callable object which takes no argument.
971 nruns : int
971 nruns : int
972 Number of times to execute `run`.
972 Number of times to execute `run`.
973
973
974 """
974 """
975 twall0 = time.perf_counter()
975 twall0 = time.perf_counter()
976 if nruns == 1:
976 if nruns == 1:
977 t0 = clock2()
977 t0 = clock2()
978 run()
978 run()
979 t1 = clock2()
979 t1 = clock2()
980 t_usr = t1[0] - t0[0]
980 t_usr = t1[0] - t0[0]
981 t_sys = t1[1] - t0[1]
981 t_sys = t1[1] - t0[1]
982 print("\nIPython CPU timings (estimated):")
982 print("\nIPython CPU timings (estimated):")
983 print(" User : %10.2f s." % t_usr)
983 print(" User : %10.2f s." % t_usr)
984 print(" System : %10.2f s." % t_sys)
984 print(" System : %10.2f s." % t_sys)
985 else:
985 else:
986 runs = range(nruns)
986 runs = range(nruns)
987 t0 = clock2()
987 t0 = clock2()
988 for nr in runs:
988 for nr in runs:
989 run()
989 run()
990 t1 = clock2()
990 t1 = clock2()
991 t_usr = t1[0] - t0[0]
991 t_usr = t1[0] - t0[0]
992 t_sys = t1[1] - t0[1]
992 t_sys = t1[1] - t0[1]
993 print("\nIPython CPU timings (estimated):")
993 print("\nIPython CPU timings (estimated):")
994 print("Total runs performed:", nruns)
994 print("Total runs performed:", nruns)
995 print(" Times : %10s %10s" % ('Total', 'Per run'))
995 print(" Times : %10s %10s" % ('Total', 'Per run'))
996 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
996 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
997 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
997 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
998 twall1 = time.perf_counter()
998 twall1 = time.perf_counter()
999 print("Wall time: %10.2f s." % (twall1 - twall0))
999 print("Wall time: %10.2f s." % (twall1 - twall0))
1000
1000
1001 @skip_doctest
1001 @skip_doctest
1002 @no_var_expand
1002 @no_var_expand
1003 @line_cell_magic
1003 @line_cell_magic
1004 @needs_local_scope
1004 @needs_local_scope
1005 def timeit(self, line='', cell=None, local_ns=None):
1005 def timeit(self, line='', cell=None, local_ns=None):
1006 """Time execution of a Python statement or expression
1006 """Time execution of a Python statement or expression
1007
1007
1008 Usage, in line mode:
1008 Usage, in line mode:
1009 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
1009 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
1010 or in cell mode:
1010 or in cell mode:
1011 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
1011 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
1012 code
1012 code
1013 code...
1013 code...
1014
1014
1015 Time execution of a Python statement or expression using the timeit
1015 Time execution of a Python statement or expression using the timeit
1016 module. This function can be used both as a line and cell magic:
1016 module. This function can be used both as a line and cell magic:
1017
1017
1018 - In line mode you can time a single-line statement (though multiple
1018 - In line mode you can time a single-line statement (though multiple
1019 ones can be chained with using semicolons).
1019 ones can be chained with using semicolons).
1020
1020
1021 - In cell mode, the statement in the first line is used as setup code
1021 - In cell mode, the statement in the first line is used as setup code
1022 (executed but not timed) and the body of the cell is timed. The cell
1022 (executed but not timed) and the body of the cell is timed. The cell
1023 body has access to any variables created in the setup code.
1023 body has access to any variables created in the setup code.
1024
1024
1025 Options:
1025 Options:
1026 -n<N>: execute the given statement <N> times in a loop. If <N> is not
1026 -n<N>: execute the given statement <N> times in a loop. If <N> is not
1027 provided, <N> is determined so as to get sufficient accuracy.
1027 provided, <N> is determined so as to get sufficient accuracy.
1028
1028
1029 -r<R>: number of repeats <R>, each consisting of <N> loops, and take the
1029 -r<R>: number of repeats <R>, each consisting of <N> loops, and take the
1030 best result.
1030 best result.
1031 Default: 7
1031 Default: 7
1032
1032
1033 -t: use time.time to measure the time, which is the default on Unix.
1033 -t: use time.time to measure the time, which is the default on Unix.
1034 This function measures wall time.
1034 This function measures wall time.
1035
1035
1036 -c: use time.clock to measure the time, which is the default on
1036 -c: use time.clock to measure the time, which is the default on
1037 Windows and measures wall time. On Unix, resource.getrusage is used
1037 Windows and measures wall time. On Unix, resource.getrusage is used
1038 instead and returns the CPU user time.
1038 instead and returns the CPU user time.
1039
1039
1040 -p<P>: use a precision of <P> digits to display the timing result.
1040 -p<P>: use a precision of <P> digits to display the timing result.
1041 Default: 3
1041 Default: 3
1042
1042
1043 -q: Quiet, do not print result.
1043 -q: Quiet, do not print result.
1044
1044
1045 -o: return a TimeitResult that can be stored in a variable to inspect
1045 -o: return a TimeitResult that can be stored in a variable to inspect
1046 the result in more details.
1046 the result in more details.
1047
1047
1048 .. versionchanged:: 7.3
1048 .. versionchanged:: 7.3
1049 User variables are no longer expanded,
1049 User variables are no longer expanded,
1050 the magic line is always left unmodified.
1050 the magic line is always left unmodified.
1051
1051
1052 Examples
1052 Examples
1053 --------
1053 --------
1054 ::
1054 ::
1055
1055
1056 In [1]: %timeit pass
1056 In [1]: %timeit pass
1057 8.26 ns Β± 0.12 ns per loop (mean Β± std. dev. of 7 runs, 100000000 loops each)
1057 8.26 ns Β± 0.12 ns per loop (mean Β± std. dev. of 7 runs, 100000000 loops each)
1058
1058
1059 In [2]: u = None
1059 In [2]: u = None
1060
1060
1061 In [3]: %timeit u is None
1061 In [3]: %timeit u is None
1062 29.9 ns Β± 0.643 ns per loop (mean Β± std. dev. of 7 runs, 10000000 loops each)
1062 29.9 ns Β± 0.643 ns per loop (mean Β± std. dev. of 7 runs, 10000000 loops each)
1063
1063
1064 In [4]: %timeit -r 4 u == None
1064 In [4]: %timeit -r 4 u == None
1065
1065
1066 In [5]: import time
1066 In [5]: import time
1067
1067
1068 In [6]: %timeit -n1 time.sleep(2)
1068 In [6]: %timeit -n1 time.sleep(2)
1069
1069
1070
1071 The times reported by %timeit will be slightly higher than those
1070 The times reported by %timeit will be slightly higher than those
1072 reported by the timeit.py script when variables are accessed. This is
1071 reported by the timeit.py script when variables are accessed. This is
1073 due to the fact that %timeit executes the statement in the namespace
1072 due to the fact that %timeit executes the statement in the namespace
1074 of the shell, compared with timeit.py, which uses a single setup
1073 of the shell, compared with timeit.py, which uses a single setup
1075 statement to import function or create variables. Generally, the bias
1074 statement to import function or create variables. Generally, the bias
1076 does not matter as long as results from timeit.py are not mixed with
1075 does not matter as long as results from timeit.py are not mixed with
1077 those from %timeit."""
1076 those from %timeit."""
1078
1077
1079 opts, stmt = self.parse_options(
1078 opts, stmt = self.parse_options(
1080 line, "n:r:tcp:qo", posix=False, strict=False, preserve_non_opts=True
1079 line, "n:r:tcp:qo", posix=False, strict=False, preserve_non_opts=True
1081 )
1080 )
1082 if stmt == "" and cell is None:
1081 if stmt == "" and cell is None:
1083 return
1082 return
1084
1083
1085 timefunc = timeit.default_timer
1084 timefunc = timeit.default_timer
1086 number = int(getattr(opts, "n", 0))
1085 number = int(getattr(opts, "n", 0))
1087 default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat
1086 default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat
1088 repeat = int(getattr(opts, "r", default_repeat))
1087 repeat = int(getattr(opts, "r", default_repeat))
1089 precision = int(getattr(opts, "p", 3))
1088 precision = int(getattr(opts, "p", 3))
1090 quiet = 'q' in opts
1089 quiet = 'q' in opts
1091 return_result = 'o' in opts
1090 return_result = 'o' in opts
1092 if hasattr(opts, "t"):
1091 if hasattr(opts, "t"):
1093 timefunc = time.time
1092 timefunc = time.time
1094 if hasattr(opts, "c"):
1093 if hasattr(opts, "c"):
1095 timefunc = clock
1094 timefunc = clock
1096
1095
1097 timer = Timer(timer=timefunc)
1096 timer = Timer(timer=timefunc)
1098 # this code has tight coupling to the inner workings of timeit.Timer,
1097 # this code has tight coupling to the inner workings of timeit.Timer,
1099 # but is there a better way to achieve that the code stmt has access
1098 # but is there a better way to achieve that the code stmt has access
1100 # to the shell namespace?
1099 # to the shell namespace?
1101 transform = self.shell.transform_cell
1100 transform = self.shell.transform_cell
1102
1101
1103 if cell is None:
1102 if cell is None:
1104 # called as line magic
1103 # called as line magic
1105 ast_setup = self.shell.compile.ast_parse("pass")
1104 ast_setup = self.shell.compile.ast_parse("pass")
1106 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1105 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1107 else:
1106 else:
1108 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1107 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1109 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1108 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1110
1109
1111 ast_setup = self.shell.transform_ast(ast_setup)
1110 ast_setup = self.shell.transform_ast(ast_setup)
1112 ast_stmt = self.shell.transform_ast(ast_stmt)
1111 ast_stmt = self.shell.transform_ast(ast_stmt)
1113
1112
1114 # Check that these compile to valid Python code *outside* the timer func
1113 # Check that these compile to valid Python code *outside* the timer func
1115 # Invalid code may become valid when put inside the function & loop,
1114 # Invalid code may become valid when put inside the function & loop,
1116 # which messes up error messages.
1115 # which messes up error messages.
1117 # https://github.com/ipython/ipython/issues/10636
1116 # https://github.com/ipython/ipython/issues/10636
1118 self.shell.compile(ast_setup, "<magic-timeit-setup>", "exec")
1117 self.shell.compile(ast_setup, "<magic-timeit-setup>", "exec")
1119 self.shell.compile(ast_stmt, "<magic-timeit-stmt>", "exec")
1118 self.shell.compile(ast_stmt, "<magic-timeit-stmt>", "exec")
1120
1119
1121 # This codestring is taken from timeit.template - we fill it in as an
1120 # This codestring is taken from timeit.template - we fill it in as an
1122 # AST, so that we can apply our AST transformations to the user code
1121 # AST, so that we can apply our AST transformations to the user code
1123 # without affecting the timing code.
1122 # without affecting the timing code.
1124 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1123 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1125 ' setup\n'
1124 ' setup\n'
1126 ' _t0 = _timer()\n'
1125 ' _t0 = _timer()\n'
1127 ' for _i in _it:\n'
1126 ' for _i in _it:\n'
1128 ' stmt\n'
1127 ' stmt\n'
1129 ' _t1 = _timer()\n'
1128 ' _t1 = _timer()\n'
1130 ' return _t1 - _t0\n')
1129 ' return _t1 - _t0\n')
1131
1130
1132 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1131 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1133 timeit_ast = ast.fix_missing_locations(timeit_ast)
1132 timeit_ast = ast.fix_missing_locations(timeit_ast)
1134
1133
1135 # Track compilation time so it can be reported if too long
1134 # Track compilation time so it can be reported if too long
1136 # Minimum time above which compilation time will be reported
1135 # Minimum time above which compilation time will be reported
1137 tc_min = 0.1
1136 tc_min = 0.1
1138
1137
1139 t0 = clock()
1138 t0 = clock()
1140 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1139 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1141 tc = clock()-t0
1140 tc = clock()-t0
1142
1141
1143 ns = {}
1142 ns = {}
1144 glob = self.shell.user_ns
1143 glob = self.shell.user_ns
1145 # handles global vars with same name as local vars. We store them in conflict_globs.
1144 # handles global vars with same name as local vars. We store them in conflict_globs.
1146 conflict_globs = {}
1145 conflict_globs = {}
1147 if local_ns and cell is None:
1146 if local_ns and cell is None:
1148 for var_name, var_val in glob.items():
1147 for var_name, var_val in glob.items():
1149 if var_name in local_ns:
1148 if var_name in local_ns:
1150 conflict_globs[var_name] = var_val
1149 conflict_globs[var_name] = var_val
1151 glob.update(local_ns)
1150 glob.update(local_ns)
1152
1151
1153 exec(code, glob, ns)
1152 exec(code, glob, ns)
1154 timer.inner = ns["inner"]
1153 timer.inner = ns["inner"]
1155
1154
1156 # This is used to check if there is a huge difference between the
1155 # This is used to check if there is a huge difference between the
1157 # best and worst timings.
1156 # best and worst timings.
1158 # Issue: https://github.com/ipython/ipython/issues/6471
1157 # Issue: https://github.com/ipython/ipython/issues/6471
1159 if number == 0:
1158 if number == 0:
1160 # determine number so that 0.2 <= total time < 2.0
1159 # determine number so that 0.2 <= total time < 2.0
1161 for index in range(0, 10):
1160 for index in range(0, 10):
1162 number = 10 ** index
1161 number = 10 ** index
1163 time_number = timer.timeit(number)
1162 time_number = timer.timeit(number)
1164 if time_number >= 0.2:
1163 if time_number >= 0.2:
1165 break
1164 break
1166
1165
1167 all_runs = timer.repeat(repeat, number)
1166 all_runs = timer.repeat(repeat, number)
1168 best = min(all_runs) / number
1167 best = min(all_runs) / number
1169 worst = max(all_runs) / number
1168 worst = max(all_runs) / number
1170 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1169 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1171
1170
1172 # Restore global vars from conflict_globs
1171 # Restore global vars from conflict_globs
1173 if conflict_globs:
1172 if conflict_globs:
1174 glob.update(conflict_globs)
1173 glob.update(conflict_globs)
1175
1174
1176 if not quiet :
1175 if not quiet :
1177 # Check best timing is greater than zero to avoid a
1176 # Check best timing is greater than zero to avoid a
1178 # ZeroDivisionError.
1177 # ZeroDivisionError.
1179 # In cases where the slowest timing is lesser than a microsecond
1178 # In cases where the slowest timing is lesser than a microsecond
1180 # we assume that it does not really matter if the fastest
1179 # we assume that it does not really matter if the fastest
1181 # timing is 4 times faster than the slowest timing or not.
1180 # timing is 4 times faster than the slowest timing or not.
1182 if worst > 4 * best and best > 0 and worst > 1e-6:
1181 if worst > 4 * best and best > 0 and worst > 1e-6:
1183 print("The slowest run took %0.2f times longer than the "
1182 print("The slowest run took %0.2f times longer than the "
1184 "fastest. This could mean that an intermediate result "
1183 "fastest. This could mean that an intermediate result "
1185 "is being cached." % (worst / best))
1184 "is being cached." % (worst / best))
1186
1185
1187 print( timeit_result )
1186 print( timeit_result )
1188
1187
1189 if tc > tc_min:
1188 if tc > tc_min:
1190 print("Compiler time: %.2f s" % tc)
1189 print("Compiler time: %.2f s" % tc)
1191 if return_result:
1190 if return_result:
1192 return timeit_result
1191 return timeit_result
1193
1192
1194 @skip_doctest
1193 @skip_doctest
1195 @no_var_expand
1194 @no_var_expand
1196 @needs_local_scope
1195 @needs_local_scope
1197 @line_cell_magic
1196 @line_cell_magic
1198 def time(self,line='', cell=None, local_ns=None):
1197 def time(self,line='', cell=None, local_ns=None):
1199 """Time execution of a Python statement or expression.
1198 """Time execution of a Python statement or expression.
1200
1199
1201 The CPU and wall clock times are printed, and the value of the
1200 The CPU and wall clock times are printed, and the value of the
1202 expression (if any) is returned. Note that under Win32, system time
1201 expression (if any) is returned. Note that under Win32, system time
1203 is always reported as 0, since it can not be measured.
1202 is always reported as 0, since it can not be measured.
1204
1203
1205 This function can be used both as a line and cell magic:
1204 This function can be used both as a line and cell magic:
1206
1205
1207 - In line mode you can time a single-line statement (though multiple
1206 - In line mode you can time a single-line statement (though multiple
1208 ones can be chained with using semicolons).
1207 ones can be chained with using semicolons).
1209
1208
1210 - In cell mode, you can time the cell body (a directly
1209 - In cell mode, you can time the cell body (a directly
1211 following statement raises an error).
1210 following statement raises an error).
1212
1211
1213 This function provides very basic timing functionality. Use the timeit
1212 This function provides very basic timing functionality. Use the timeit
1214 magic for more control over the measurement.
1213 magic for more control over the measurement.
1215
1214
1216 .. versionchanged:: 7.3
1215 .. versionchanged:: 7.3
1217 User variables are no longer expanded,
1216 User variables are no longer expanded,
1218 the magic line is always left unmodified.
1217 the magic line is always left unmodified.
1219
1218
1220 Examples
1219 Examples
1221 --------
1220 --------
1222 ::
1221 ::
1223
1222
1224 In [1]: %time 2**128
1223 In [1]: %time 2**128
1225 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1224 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1226 Wall time: 0.00
1225 Wall time: 0.00
1227 Out[1]: 340282366920938463463374607431768211456L
1226 Out[1]: 340282366920938463463374607431768211456L
1228
1227
1229 In [2]: n = 1000000
1228 In [2]: n = 1000000
1230
1229
1231 In [3]: %time sum(range(n))
1230 In [3]: %time sum(range(n))
1232 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1231 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1233 Wall time: 1.37
1232 Wall time: 1.37
1234 Out[3]: 499999500000L
1233 Out[3]: 499999500000L
1235
1234
1236 In [4]: %time print 'hello world'
1235 In [4]: %time print 'hello world'
1237 hello world
1236 hello world
1238 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1237 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1239 Wall time: 0.00
1238 Wall time: 0.00
1240
1239
1241
1242 .. note::
1240 .. note::
1243 The time needed by Python to compile the given expression will be
1241 The time needed by Python to compile the given expression will be
1244 reported if it is more than 0.1s.
1242 reported if it is more than 0.1s.
1245
1243
1246 In the example below, the actual exponentiation is done by Python
1244 In the example below, the actual exponentiation is done by Python
1247 at compilation time, so while the expression can take a noticeable
1245 at compilation time, so while the expression can take a noticeable
1248 amount of time to compute, that time is purely due to the
1246 amount of time to compute, that time is purely due to the
1249 compilation::
1247 compilation::
1250
1248
1251 In [5]: %time 3**9999;
1249 In [5]: %time 3**9999;
1252 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1250 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1253 Wall time: 0.00 s
1251 Wall time: 0.00 s
1254
1252
1255 In [6]: %time 3**999999;
1253 In [6]: %time 3**999999;
1256 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1254 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1257 Wall time: 0.00 s
1255 Wall time: 0.00 s
1258 Compiler : 0.78 s
1256 Compiler : 0.78 s
1259 """
1257 """
1260 # fail immediately if the given expression can't be compiled
1258 # fail immediately if the given expression can't be compiled
1261
1259
1262 if line and cell:
1260 if line and cell:
1263 raise UsageError("Can't use statement directly after '%%time'!")
1261 raise UsageError("Can't use statement directly after '%%time'!")
1264
1262
1265 if cell:
1263 if cell:
1266 expr = self.shell.transform_cell(cell)
1264 expr = self.shell.transform_cell(cell)
1267 else:
1265 else:
1268 expr = self.shell.transform_cell(line)
1266 expr = self.shell.transform_cell(line)
1269
1267
1270 # Minimum time above which parse time will be reported
1268 # Minimum time above which parse time will be reported
1271 tp_min = 0.1
1269 tp_min = 0.1
1272
1270
1273 t0 = clock()
1271 t0 = clock()
1274 expr_ast = self.shell.compile.ast_parse(expr)
1272 expr_ast = self.shell.compile.ast_parse(expr)
1275 tp = clock()-t0
1273 tp = clock()-t0
1276
1274
1277 # Apply AST transformations
1275 # Apply AST transformations
1278 expr_ast = self.shell.transform_ast(expr_ast)
1276 expr_ast = self.shell.transform_ast(expr_ast)
1279
1277
1280 # Minimum time above which compilation time will be reported
1278 # Minimum time above which compilation time will be reported
1281 tc_min = 0.1
1279 tc_min = 0.1
1282
1280
1283 expr_val=None
1281 expr_val=None
1284 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1282 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1285 mode = 'eval'
1283 mode = 'eval'
1286 source = '<timed eval>'
1284 source = '<timed eval>'
1287 expr_ast = ast.Expression(expr_ast.body[0].value)
1285 expr_ast = ast.Expression(expr_ast.body[0].value)
1288 else:
1286 else:
1289 mode = 'exec'
1287 mode = 'exec'
1290 source = '<timed exec>'
1288 source = '<timed exec>'
1291 # multi-line %%time case
1289 # multi-line %%time case
1292 if len(expr_ast.body) > 1 and isinstance(expr_ast.body[-1], ast.Expr):
1290 if len(expr_ast.body) > 1 and isinstance(expr_ast.body[-1], ast.Expr):
1293 expr_val= expr_ast.body[-1]
1291 expr_val= expr_ast.body[-1]
1294 expr_ast = expr_ast.body[:-1]
1292 expr_ast = expr_ast.body[:-1]
1295 expr_ast = Module(expr_ast, [])
1293 expr_ast = Module(expr_ast, [])
1296 expr_val = ast.Expression(expr_val.value)
1294 expr_val = ast.Expression(expr_val.value)
1297
1295
1298 t0 = clock()
1296 t0 = clock()
1299 code = self.shell.compile(expr_ast, source, mode)
1297 code = self.shell.compile(expr_ast, source, mode)
1300 tc = clock()-t0
1298 tc = clock()-t0
1301
1299
1302 # skew measurement as little as possible
1300 # skew measurement as little as possible
1303 glob = self.shell.user_ns
1301 glob = self.shell.user_ns
1304 wtime = time.time
1302 wtime = time.time
1305 # time execution
1303 # time execution
1306 wall_st = wtime()
1304 wall_st = wtime()
1307 if mode=='eval':
1305 if mode=='eval':
1308 st = clock2()
1306 st = clock2()
1309 try:
1307 try:
1310 out = eval(code, glob, local_ns)
1308 out = eval(code, glob, local_ns)
1311 except:
1309 except:
1312 self.shell.showtraceback()
1310 self.shell.showtraceback()
1313 return
1311 return
1314 end = clock2()
1312 end = clock2()
1315 else:
1313 else:
1316 st = clock2()
1314 st = clock2()
1317 try:
1315 try:
1318 exec(code, glob, local_ns)
1316 exec(code, glob, local_ns)
1319 out=None
1317 out=None
1320 # multi-line %%time case
1318 # multi-line %%time case
1321 if expr_val is not None:
1319 if expr_val is not None:
1322 code_2 = self.shell.compile(expr_val, source, 'eval')
1320 code_2 = self.shell.compile(expr_val, source, 'eval')
1323 out = eval(code_2, glob, local_ns)
1321 out = eval(code_2, glob, local_ns)
1324 except:
1322 except:
1325 self.shell.showtraceback()
1323 self.shell.showtraceback()
1326 return
1324 return
1327 end = clock2()
1325 end = clock2()
1328
1326
1329 wall_end = wtime()
1327 wall_end = wtime()
1330 # Compute actual times and report
1328 # Compute actual times and report
1331 wall_time = wall_end-wall_st
1329 wall_time = wall_end-wall_st
1332 cpu_user = end[0]-st[0]
1330 cpu_user = end[0]-st[0]
1333 cpu_sys = end[1]-st[1]
1331 cpu_sys = end[1]-st[1]
1334 cpu_tot = cpu_user+cpu_sys
1332 cpu_tot = cpu_user+cpu_sys
1335 # On windows cpu_sys is always zero, so no new information to the next print
1333 # On windows cpu_sys is always zero, so no new information to the next print
1336 if sys.platform != 'win32':
1334 if sys.platform != 'win32':
1337 print("CPU times: user %s, sys: %s, total: %s" % \
1335 print("CPU times: user %s, sys: %s, total: %s" % \
1338 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1336 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1339 print("Wall time: %s" % _format_time(wall_time))
1337 print("Wall time: %s" % _format_time(wall_time))
1340 if tc > tc_min:
1338 if tc > tc_min:
1341 print("Compiler : %s" % _format_time(tc))
1339 print("Compiler : %s" % _format_time(tc))
1342 if tp > tp_min:
1340 if tp > tp_min:
1343 print("Parser : %s" % _format_time(tp))
1341 print("Parser : %s" % _format_time(tp))
1344 return out
1342 return out
1345
1343
1346 @skip_doctest
1344 @skip_doctest
1347 @line_magic
1345 @line_magic
1348 def macro(self, parameter_s=''):
1346 def macro(self, parameter_s=''):
1349 """Define a macro for future re-execution. It accepts ranges of history,
1347 """Define a macro for future re-execution. It accepts ranges of history,
1350 filenames or string objects.
1348 filenames or string objects.
1351
1349
1352 Usage:\\
1350 Usage:\\
1353 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1351 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1354
1352
1355 Options:
1353 Options:
1356
1354
1357 -r: use 'raw' input. By default, the 'processed' history is used,
1355 -r: use 'raw' input. By default, the 'processed' history is used,
1358 so that magics are loaded in their transformed version to valid
1356 so that magics are loaded in their transformed version to valid
1359 Python. If this option is given, the raw input as typed at the
1357 Python. If this option is given, the raw input as typed at the
1360 command line is used instead.
1358 command line is used instead.
1361
1359
1362 -q: quiet macro definition. By default, a tag line is printed
1360 -q: quiet macro definition. By default, a tag line is printed
1363 to indicate the macro has been created, and then the contents of
1361 to indicate the macro has been created, and then the contents of
1364 the macro are printed. If this option is given, then no printout
1362 the macro are printed. If this option is given, then no printout
1365 is produced once the macro is created.
1363 is produced once the macro is created.
1366
1364
1367 This will define a global variable called `name` which is a string
1365 This will define a global variable called `name` which is a string
1368 made of joining the slices and lines you specify (n1,n2,... numbers
1366 made of joining the slices and lines you specify (n1,n2,... numbers
1369 above) from your input history into a single string. This variable
1367 above) from your input history into a single string. This variable
1370 acts like an automatic function which re-executes those lines as if
1368 acts like an automatic function which re-executes those lines as if
1371 you had typed them. You just type 'name' at the prompt and the code
1369 you had typed them. You just type 'name' at the prompt and the code
1372 executes.
1370 executes.
1373
1371
1374 The syntax for indicating input ranges is described in %history.
1372 The syntax for indicating input ranges is described in %history.
1375
1373
1376 Note: as a 'hidden' feature, you can also use traditional python slice
1374 Note: as a 'hidden' feature, you can also use traditional python slice
1377 notation, where N:M means numbers N through M-1.
1375 notation, where N:M means numbers N through M-1.
1378
1376
1379 For example, if your history contains (print using %hist -n )::
1377 For example, if your history contains (print using %hist -n )::
1380
1378
1381 44: x=1
1379 44: x=1
1382 45: y=3
1380 45: y=3
1383 46: z=x+y
1381 46: z=x+y
1384 47: print x
1382 47: print x
1385 48: a=5
1383 48: a=5
1386 49: print 'x',x,'y',y
1384 49: print 'x',x,'y',y
1387
1385
1388 you can create a macro with lines 44 through 47 (included) and line 49
1386 you can create a macro with lines 44 through 47 (included) and line 49
1389 called my_macro with::
1387 called my_macro with::
1390
1388
1391 In [55]: %macro my_macro 44-47 49
1389 In [55]: %macro my_macro 44-47 49
1392
1390
1393 Now, typing `my_macro` (without quotes) will re-execute all this code
1391 Now, typing `my_macro` (without quotes) will re-execute all this code
1394 in one pass.
1392 in one pass.
1395
1393
1396 You don't need to give the line-numbers in order, and any given line
1394 You don't need to give the line-numbers in order, and any given line
1397 number can appear multiple times. You can assemble macros with any
1395 number can appear multiple times. You can assemble macros with any
1398 lines from your input history in any order.
1396 lines from your input history in any order.
1399
1397
1400 The macro is a simple object which holds its value in an attribute,
1398 The macro is a simple object which holds its value in an attribute,
1401 but IPython's display system checks for macros and executes them as
1399 but IPython's display system checks for macros and executes them as
1402 code instead of printing them when you type their name.
1400 code instead of printing them when you type their name.
1403
1401
1404 You can view a macro's contents by explicitly printing it with::
1402 You can view a macro's contents by explicitly printing it with::
1405
1403
1406 print macro_name
1404 print macro_name
1407
1405
1408 """
1406 """
1409 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1407 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1410 if not args: # List existing macros
1408 if not args: # List existing macros
1411 return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro))
1409 return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro))
1412 if len(args) == 1:
1410 if len(args) == 1:
1413 raise UsageError(
1411 raise UsageError(
1414 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1412 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1415 name, codefrom = args[0], " ".join(args[1:])
1413 name, codefrom = args[0], " ".join(args[1:])
1416
1414
1417 #print 'rng',ranges # dbg
1415 #print 'rng',ranges # dbg
1418 try:
1416 try:
1419 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1417 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1420 except (ValueError, TypeError) as e:
1418 except (ValueError, TypeError) as e:
1421 print(e.args[0])
1419 print(e.args[0])
1422 return
1420 return
1423 macro = Macro(lines)
1421 macro = Macro(lines)
1424 self.shell.define_macro(name, macro)
1422 self.shell.define_macro(name, macro)
1425 if not ( 'q' in opts) :
1423 if not ( 'q' in opts) :
1426 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1424 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1427 print('=== Macro contents: ===')
1425 print('=== Macro contents: ===')
1428 print(macro, end=' ')
1426 print(macro, end=' ')
1429
1427
1430 @magic_arguments.magic_arguments()
1428 @magic_arguments.magic_arguments()
1431 @magic_arguments.argument('output', type=str, default='', nargs='?',
1429 @magic_arguments.argument('output', type=str, default='', nargs='?',
1432 help="""The name of the variable in which to store output.
1430 help="""The name of the variable in which to store output.
1433 This is a utils.io.CapturedIO object with stdout/err attributes
1431 This is a utils.io.CapturedIO object with stdout/err attributes
1434 for the text of the captured output.
1432 for the text of the captured output.
1435
1433
1436 CapturedOutput also has a show() method for displaying the output,
1434 CapturedOutput also has a show() method for displaying the output,
1437 and __call__ as well, so you can use that to quickly display the
1435 and __call__ as well, so you can use that to quickly display the
1438 output.
1436 output.
1439
1437
1440 If unspecified, captured output is discarded.
1438 If unspecified, captured output is discarded.
1441 """
1439 """
1442 )
1440 )
1443 @magic_arguments.argument('--no-stderr', action="store_true",
1441 @magic_arguments.argument('--no-stderr', action="store_true",
1444 help="""Don't capture stderr."""
1442 help="""Don't capture stderr."""
1445 )
1443 )
1446 @magic_arguments.argument('--no-stdout', action="store_true",
1444 @magic_arguments.argument('--no-stdout', action="store_true",
1447 help="""Don't capture stdout."""
1445 help="""Don't capture stdout."""
1448 )
1446 )
1449 @magic_arguments.argument('--no-display', action="store_true",
1447 @magic_arguments.argument('--no-display', action="store_true",
1450 help="""Don't capture IPython's rich display."""
1448 help="""Don't capture IPython's rich display."""
1451 )
1449 )
1452 @cell_magic
1450 @cell_magic
1453 def capture(self, line, cell):
1451 def capture(self, line, cell):
1454 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1452 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1455 args = magic_arguments.parse_argstring(self.capture, line)
1453 args = magic_arguments.parse_argstring(self.capture, line)
1456 out = not args.no_stdout
1454 out = not args.no_stdout
1457 err = not args.no_stderr
1455 err = not args.no_stderr
1458 disp = not args.no_display
1456 disp = not args.no_display
1459 with capture_output(out, err, disp) as io:
1457 with capture_output(out, err, disp) as io:
1460 self.shell.run_cell(cell)
1458 self.shell.run_cell(cell)
1461 if args.output:
1459 if args.output:
1462 self.shell.user_ns[args.output] = io
1460 self.shell.user_ns[args.output] = io
1463
1461
1464 def parse_breakpoint(text, current_file):
1462 def parse_breakpoint(text, current_file):
1465 '''Returns (file, line) for file:line and (current_file, line) for line'''
1463 '''Returns (file, line) for file:line and (current_file, line) for line'''
1466 colon = text.find(':')
1464 colon = text.find(':')
1467 if colon == -1:
1465 if colon == -1:
1468 return current_file, int(text)
1466 return current_file, int(text)
1469 else:
1467 else:
1470 return text[:colon], int(text[colon+1:])
1468 return text[:colon], int(text[colon+1:])
1471
1469
1472 def _format_time(timespan, precision=3):
1470 def _format_time(timespan, precision=3):
1473 """Formats the timespan in a human readable form"""
1471 """Formats the timespan in a human readable form"""
1474
1472
1475 if timespan >= 60.0:
1473 if timespan >= 60.0:
1476 # we have more than a minute, format that in a human readable form
1474 # we have more than a minute, format that in a human readable form
1477 # Idea from http://snipplr.com/view/5713/
1475 # Idea from http://snipplr.com/view/5713/
1478 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1476 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1479 time = []
1477 time = []
1480 leftover = timespan
1478 leftover = timespan
1481 for suffix, length in parts:
1479 for suffix, length in parts:
1482 value = int(leftover / length)
1480 value = int(leftover / length)
1483 if value > 0:
1481 if value > 0:
1484 leftover = leftover % length
1482 leftover = leftover % length
1485 time.append(u'%s%s' % (str(value), suffix))
1483 time.append(u'%s%s' % (str(value), suffix))
1486 if leftover < 1:
1484 if leftover < 1:
1487 break
1485 break
1488 return " ".join(time)
1486 return " ".join(time)
1489
1487
1490
1488
1491 # Unfortunately the unicode 'micro' symbol can cause problems in
1489 # Unfortunately the unicode 'micro' symbol can cause problems in
1492 # certain terminals.
1490 # certain terminals.
1493 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1491 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1494 # Try to prevent crashes by being more secure than it needs to
1492 # Try to prevent crashes by being more secure than it needs to
1495 # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set.
1493 # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set.
1496 units = [u"s", u"ms",u'us',"ns"] # the save value
1494 units = [u"s", u"ms",u'us',"ns"] # the save value
1497 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1495 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1498 try:
1496 try:
1499 u'\xb5'.encode(sys.stdout.encoding)
1497 u'\xb5'.encode(sys.stdout.encoding)
1500 units = [u"s", u"ms",u'\xb5s',"ns"]
1498 units = [u"s", u"ms",u'\xb5s',"ns"]
1501 except:
1499 except:
1502 pass
1500 pass
1503 scaling = [1, 1e3, 1e6, 1e9]
1501 scaling = [1, 1e3, 1e6, 1e9]
1504
1502
1505 if timespan > 0.0:
1503 if timespan > 0.0:
1506 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1504 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1507 else:
1505 else:
1508 order = 3
1506 order = 3
1509 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
1507 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
@@ -1,63 +1,63 b''
1 """Implementation of magic functions for the extension machinery.
1 """Implementation of magic functions for the extension machinery.
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
14
15
15
16 # Our own packages
16 # Our own packages
17 from IPython.core.error import UsageError
17 from IPython.core.error import UsageError
18 from IPython.core.magic import Magics, magics_class, line_magic
18 from IPython.core.magic import Magics, magics_class, line_magic
19
19
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21 # Magic implementation classes
21 # Magic implementation classes
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23
23
24 @magics_class
24 @magics_class
25 class ExtensionMagics(Magics):
25 class ExtensionMagics(Magics):
26 """Magics to manage the IPython extensions system."""
26 """Magics to manage the IPython extensions system."""
27
27
28 @line_magic
28 @line_magic
29 def load_ext(self, module_str):
29 def load_ext(self, module_str):
30 """Load an IPython extension by its module name."""
30 """Load an IPython extension by its module name."""
31 if not module_str:
31 if not module_str:
32 raise UsageError('Missing module name.')
32 raise UsageError('Missing module name.')
33 res = self.shell.extension_manager.load_extension(module_str)
33 res = self.shell.extension_manager.load_extension(module_str)
34
34
35 if res == 'already loaded':
35 if res == 'already loaded':
36 print("The %s extension is already loaded. To reload it, use:" % module_str)
36 print("The %s extension is already loaded. To reload it, use:" % module_str)
37 print(" %reload_ext", module_str)
37 print(" %reload_ext", module_str)
38 elif res == 'no load function':
38 elif res == 'no load function':
39 print("The %s module is not an IPython extension." % module_str)
39 print("The %s module is not an IPython extension." % module_str)
40
40
41 @line_magic
41 @line_magic
42 def unload_ext(self, module_str):
42 def unload_ext(self, module_str):
43 """Unload an IPython extension by its module name.
43 """Unload an IPython extension by its module name.
44
44
45 Not all extensions can be unloaded, only those which define an
45 Not all extensions can be unloaded, only those which define an
46 ``unload_ipython_extension`` function.
46 ``unload_ipython_extension`` function.
47 """
47 """
48 if not module_str:
48 if not module_str:
49 raise UsageError('Missing module name.')
49 raise UsageError('Missing module name.')
50
50
51 res = self.shell.extension_manager.unload_extension(module_str)
51 res = self.shell.extension_manager.unload_extension(module_str)
52
52
53 if res == 'no unload function':
53 if res == 'no unload function':
54 print("The %s extension doesn't define how to unload it." % module_str)
54 print("The %s extension doesn't define how to unload it." % module_str)
55 elif res == "not loaded":
55 elif res == "not loaded":
56 print("The %s extension is not loaded." % module_str)
56 print("The %s extension is not loaded." % module_str)
57
57
58 @line_magic
58 @line_magic
59 def reload_ext(self, module_str):
59 def reload_ext(self, module_str):
60 """Reload an IPython extension by its module name."""
60 """Reload an IPython extension by its module name."""
61 if not module_str:
61 if not module_str:
62 raise UsageError('Missing module name.')
62 raise UsageError('Missing module name.')
63 self.shell.extension_manager.reload_extension(module_str)
63 self.shell.extension_manager.reload_extension(module_str)
@@ -1,337 +1,337 b''
1 """Implementation of magic functions related to History.
1 """Implementation of magic functions related to History.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012, IPython Development Team.
4 # Copyright (c) 2012, 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
14
15 # Stdlib
15 # Stdlib
16 import os
16 import os
17 import sys
17 import sys
18 from io import open as io_open
18 from io import open as io_open
19 import fnmatch
19 import fnmatch
20
20
21 # Our own packages
21 # Our own packages
22 from IPython.core.error import StdinNotImplementedError
22 from IPython.core.error import StdinNotImplementedError
23 from IPython.core.magic import Magics, magics_class, line_magic
23 from IPython.core.magic import Magics, magics_class, line_magic
24 from IPython.core.magic_arguments import (argument, magic_arguments,
24 from IPython.core.magic_arguments import (argument, magic_arguments,
25 parse_argstring)
25 parse_argstring)
26 from IPython.testing.skipdoctest import skip_doctest
26 from IPython.testing.skipdoctest import skip_doctest
27 from IPython.utils import io
27 from IPython.utils import io
28
28
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30 # Magics class implementation
30 # Magics class implementation
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32
32
33
33
34 _unspecified = object()
34 _unspecified = object()
35
35
36
36
37 @magics_class
37 @magics_class
38 class HistoryMagics(Magics):
38 class HistoryMagics(Magics):
39
39
40 @magic_arguments()
40 @magic_arguments()
41 @argument(
41 @argument(
42 '-n', dest='print_nums', action='store_true', default=False,
42 '-n', dest='print_nums', action='store_true', default=False,
43 help="""
43 help="""
44 print line numbers for each input.
44 print line numbers for each input.
45 This feature is only available if numbered prompts are in use.
45 This feature is only available if numbered prompts are in use.
46 """)
46 """)
47 @argument(
47 @argument(
48 '-o', dest='get_output', action='store_true', default=False,
48 '-o', dest='get_output', action='store_true', default=False,
49 help="also print outputs for each input.")
49 help="also print outputs for each input.")
50 @argument(
50 @argument(
51 '-p', dest='pyprompts', action='store_true', default=False,
51 '-p', dest='pyprompts', action='store_true', default=False,
52 help="""
52 help="""
53 print classic '>>>' python prompts before each input.
53 print classic '>>>' python prompts before each input.
54 This is useful for making documentation, and in conjunction
54 This is useful for making documentation, and in conjunction
55 with -o, for producing doctest-ready output.
55 with -o, for producing doctest-ready output.
56 """)
56 """)
57 @argument(
57 @argument(
58 '-t', dest='raw', action='store_false', default=True,
58 '-t', dest='raw', action='store_false', default=True,
59 help="""
59 help="""
60 print the 'translated' history, as IPython understands it.
60 print the 'translated' history, as IPython understands it.
61 IPython filters your input and converts it all into valid Python
61 IPython filters your input and converts it all into valid Python
62 source before executing it (things like magics or aliases are turned
62 source before executing it (things like magics or aliases are turned
63 into function calls, for example). With this option, you'll see the
63 into function calls, for example). With this option, you'll see the
64 native history instead of the user-entered version: '%%cd /' will be
64 native history instead of the user-entered version: '%%cd /' will be
65 seen as 'get_ipython().run_line_magic("cd", "/")' instead of '%%cd /'.
65 seen as 'get_ipython().run_line_magic("cd", "/")' instead of '%%cd /'.
66 """)
66 """)
67 @argument(
67 @argument(
68 '-f', dest='filename',
68 '-f', dest='filename',
69 help="""
69 help="""
70 FILENAME: instead of printing the output to the screen, redirect
70 FILENAME: instead of printing the output to the screen, redirect
71 it to the given file. The file is always overwritten, though *when
71 it to the given file. The file is always overwritten, though *when
72 it can*, IPython asks for confirmation first. In particular, running
72 it can*, IPython asks for confirmation first. In particular, running
73 the command 'history -f FILENAME' from the IPython Notebook
73 the command 'history -f FILENAME' from the IPython Notebook
74 interface will replace FILENAME even if it already exists *without*
74 interface will replace FILENAME even if it already exists *without*
75 confirmation.
75 confirmation.
76 """)
76 """)
77 @argument(
77 @argument(
78 '-g', dest='pattern', nargs='*', default=None,
78 '-g', dest='pattern', nargs='*', default=None,
79 help="""
79 help="""
80 treat the arg as a glob pattern to search for in (full) history.
80 treat the arg as a glob pattern to search for in (full) history.
81 This includes the saved history (almost all commands ever written).
81 This includes the saved history (almost all commands ever written).
82 The pattern may contain '?' to match one unknown character and '*'
82 The pattern may contain '?' to match one unknown character and '*'
83 to match any number of unknown characters. Use '%%hist -g' to show
83 to match any number of unknown characters. Use '%%hist -g' to show
84 full saved history (may be very long).
84 full saved history (may be very long).
85 """)
85 """)
86 @argument(
86 @argument(
87 '-l', dest='limit', type=int, nargs='?', default=_unspecified,
87 '-l', dest='limit', type=int, nargs='?', default=_unspecified,
88 help="""
88 help="""
89 get the last n lines from all sessions. Specify n as a single
89 get the last n lines from all sessions. Specify n as a single
90 arg, or the default is the last 10 lines.
90 arg, or the default is the last 10 lines.
91 """)
91 """)
92 @argument(
92 @argument(
93 '-u', dest='unique', action='store_true',
93 '-u', dest='unique', action='store_true',
94 help="""
94 help="""
95 when searching history using `-g`, show only unique history.
95 when searching history using `-g`, show only unique history.
96 """)
96 """)
97 @argument('range', nargs='*')
97 @argument('range', nargs='*')
98 @skip_doctest
98 @skip_doctest
99 @line_magic
99 @line_magic
100 def history(self, parameter_s = ''):
100 def history(self, parameter_s = ''):
101 """Print input history (_i<n> variables), with most recent last.
101 """Print input history (_i<n> variables), with most recent last.
102
102
103 By default, input history is printed without line numbers so it can be
103 By default, input history is printed without line numbers so it can be
104 directly pasted into an editor. Use -n to show them.
104 directly pasted into an editor. Use -n to show them.
105
105
106 By default, all input history from the current session is displayed.
106 By default, all input history from the current session is displayed.
107 Ranges of history can be indicated using the syntax:
107 Ranges of history can be indicated using the syntax:
108
108
109 ``4``
109 ``4``
110 Line 4, current session
110 Line 4, current session
111 ``4-6``
111 ``4-6``
112 Lines 4-6, current session
112 Lines 4-6, current session
113 ``243/1-5``
113 ``243/1-5``
114 Lines 1-5, session 243
114 Lines 1-5, session 243
115 ``~2/7``
115 ``~2/7``
116 Line 7, session 2 before current
116 Line 7, session 2 before current
117 ``~8/1-~6/5``
117 ``~8/1-~6/5``
118 From the first line of 8 sessions ago, to the fifth line of 6
118 From the first line of 8 sessions ago, to the fifth line of 6
119 sessions ago.
119 sessions ago.
120
120
121 Multiple ranges can be entered, separated by spaces
121 Multiple ranges can be entered, separated by spaces
122
122
123 The same syntax is used by %macro, %save, %edit, %rerun
123 The same syntax is used by %macro, %save, %edit, %rerun
124
124
125 Examples
125 Examples
126 --------
126 --------
127 ::
127 ::
128
128
129 In [6]: %history -n 4-6
129 In [6]: %history -n 4-6
130 4:a = 12
130 4:a = 12
131 5:print a**2
131 5:print a**2
132 6:%history -n 4-6
132 6:%history -n 4-6
133
133
134 """
134 """
135
135
136 args = parse_argstring(self.history, parameter_s)
136 args = parse_argstring(self.history, parameter_s)
137
137
138 # For brevity
138 # For brevity
139 history_manager = self.shell.history_manager
139 history_manager = self.shell.history_manager
140
140
141 def _format_lineno(session, line):
141 def _format_lineno(session, line):
142 """Helper function to format line numbers properly."""
142 """Helper function to format line numbers properly."""
143 if session in (0, history_manager.session_number):
143 if session in (0, history_manager.session_number):
144 return str(line)
144 return str(line)
145 return "%s/%s" % (session, line)
145 return "%s/%s" % (session, line)
146
146
147 # Check if output to specific file was requested.
147 # Check if output to specific file was requested.
148 outfname = args.filename
148 outfname = args.filename
149 if not outfname:
149 if not outfname:
150 outfile = sys.stdout # default
150 outfile = sys.stdout # default
151 # We don't want to close stdout at the end!
151 # We don't want to close stdout at the end!
152 close_at_end = False
152 close_at_end = False
153 else:
153 else:
154 if os.path.exists(outfname):
154 if os.path.exists(outfname):
155 try:
155 try:
156 ans = io.ask_yes_no("File %r exists. Overwrite?" % outfname)
156 ans = io.ask_yes_no("File %r exists. Overwrite?" % outfname)
157 except StdinNotImplementedError:
157 except StdinNotImplementedError:
158 ans = True
158 ans = True
159 if not ans:
159 if not ans:
160 print('Aborting.')
160 print('Aborting.')
161 return
161 return
162 print("Overwriting file.")
162 print("Overwriting file.")
163 outfile = io_open(outfname, 'w', encoding='utf-8')
163 outfile = io_open(outfname, 'w', encoding='utf-8')
164 close_at_end = True
164 close_at_end = True
165
165
166 print_nums = args.print_nums
166 print_nums = args.print_nums
167 get_output = args.get_output
167 get_output = args.get_output
168 pyprompts = args.pyprompts
168 pyprompts = args.pyprompts
169 raw = args.raw
169 raw = args.raw
170
170
171 pattern = None
171 pattern = None
172 limit = None if args.limit is _unspecified else args.limit
172 limit = None if args.limit is _unspecified else args.limit
173
173
174 range_pattern = False
174 range_pattern = False
175 if args.pattern is not None and not args.range:
175 if args.pattern is not None and not args.range:
176 if args.pattern:
176 if args.pattern:
177 pattern = "*" + " ".join(args.pattern) + "*"
177 pattern = "*" + " ".join(args.pattern) + "*"
178 else:
178 else:
179 pattern = "*"
179 pattern = "*"
180 hist = history_manager.search(pattern, raw=raw, output=get_output,
180 hist = history_manager.search(pattern, raw=raw, output=get_output,
181 n=limit, unique=args.unique)
181 n=limit, unique=args.unique)
182 print_nums = True
182 print_nums = True
183 elif args.limit is not _unspecified:
183 elif args.limit is not _unspecified:
184 n = 10 if limit is None else limit
184 n = 10 if limit is None else limit
185 hist = history_manager.get_tail(n, raw=raw, output=get_output)
185 hist = history_manager.get_tail(n, raw=raw, output=get_output)
186 else:
186 else:
187 if args.pattern:
187 if args.pattern:
188 range_pattern = "*" + " ".join(args.pattern) + "*"
188 range_pattern = "*" + " ".join(args.pattern) + "*"
189 print_nums = True
189 print_nums = True
190 hist = history_manager.get_range_by_str(
190 hist = history_manager.get_range_by_str(
191 " ".join(args.range), raw, get_output
191 " ".join(args.range), raw, get_output
192 )
192 )
193
193
194 # We could be displaying the entire history, so let's not try to pull
194 # We could be displaying the entire history, so let's not try to pull
195 # it into a list in memory. Anything that needs more space will just
195 # it into a list in memory. Anything that needs more space will just
196 # misalign.
196 # misalign.
197 width = 4
197 width = 4
198
198
199 for session, lineno, inline in hist:
199 for session, lineno, inline in hist:
200 # Print user history with tabs expanded to 4 spaces. The GUI
200 # Print user history with tabs expanded to 4 spaces. The GUI
201 # clients use hard tabs for easier usability in auto-indented code,
201 # clients use hard tabs for easier usability in auto-indented code,
202 # but we want to produce PEP-8 compliant history for safe pasting
202 # but we want to produce PEP-8 compliant history for safe pasting
203 # into an editor.
203 # into an editor.
204 if get_output:
204 if get_output:
205 inline, output = inline
205 inline, output = inline
206 if range_pattern:
206 if range_pattern:
207 if not fnmatch.fnmatch(inline, range_pattern):
207 if not fnmatch.fnmatch(inline, range_pattern):
208 continue
208 continue
209 inline = inline.expandtabs(4).rstrip()
209 inline = inline.expandtabs(4).rstrip()
210
210
211 multiline = "\n" in inline
211 multiline = "\n" in inline
212 line_sep = '\n' if multiline else ' '
212 line_sep = '\n' if multiline else ' '
213 if print_nums:
213 if print_nums:
214 print(u'%s:%s' % (_format_lineno(session, lineno).rjust(width),
214 print(u'%s:%s' % (_format_lineno(session, lineno).rjust(width),
215 line_sep), file=outfile, end=u'')
215 line_sep), file=outfile, end=u'')
216 if pyprompts:
216 if pyprompts:
217 print(u">>> ", end=u"", file=outfile)
217 print(u">>> ", end=u"", file=outfile)
218 if multiline:
218 if multiline:
219 inline = "\n... ".join(inline.splitlines()) + "\n..."
219 inline = "\n... ".join(inline.splitlines()) + "\n..."
220 print(inline, file=outfile)
220 print(inline, file=outfile)
221 if get_output and output:
221 if get_output and output:
222 print(output, file=outfile)
222 print(output, file=outfile)
223
223
224 if close_at_end:
224 if close_at_end:
225 outfile.close()
225 outfile.close()
226
226
227 @line_magic
227 @line_magic
228 def recall(self, arg):
228 def recall(self, arg):
229 r"""Repeat a command, or get command to input line for editing.
229 r"""Repeat a command, or get command to input line for editing.
230
230
231 %recall and %rep are equivalent.
231 %recall and %rep are equivalent.
232
232
233 - %recall (no arguments):
233 - %recall (no arguments):
234
234
235 Place a string version of last computation result (stored in the
235 Place a string version of last computation result (stored in the
236 special '_' variable) to the next input prompt. Allows you to create
236 special '_' variable) to the next input prompt. Allows you to create
237 elaborate command lines without using copy-paste::
237 elaborate command lines without using copy-paste::
238
238
239 In[1]: l = ["hei", "vaan"]
239 In[1]: l = ["hei", "vaan"]
240 In[2]: "".join(l)
240 In[2]: "".join(l)
241 Out[2]: heivaan
241 Out[2]: heivaan
242 In[3]: %recall
242 In[3]: %recall
243 In[4]: heivaan_ <== cursor blinking
243 In[4]: heivaan_ <== cursor blinking
244
244
245 %recall 45
245 %recall 45
246
246
247 Place history line 45 on the next input prompt. Use %hist to find
247 Place history line 45 on the next input prompt. Use %hist to find
248 out the number.
248 out the number.
249
249
250 %recall 1-4
250 %recall 1-4
251
251
252 Combine the specified lines into one cell, and place it on the next
252 Combine the specified lines into one cell, and place it on the next
253 input prompt. See %history for the slice syntax.
253 input prompt. See %history for the slice syntax.
254
254
255 %recall foo+bar
255 %recall foo+bar
256
256
257 If foo+bar can be evaluated in the user namespace, the result is
257 If foo+bar can be evaluated in the user namespace, the result is
258 placed at the next input prompt. Otherwise, the history is searched
258 placed at the next input prompt. Otherwise, the history is searched
259 for lines which contain that substring, and the most recent one is
259 for lines which contain that substring, and the most recent one is
260 placed at the next input prompt.
260 placed at the next input prompt.
261 """
261 """
262 if not arg: # Last output
262 if not arg: # Last output
263 self.shell.set_next_input(str(self.shell.user_ns["_"]))
263 self.shell.set_next_input(str(self.shell.user_ns["_"]))
264 return
264 return
265 # Get history range
265 # Get history range
266 histlines = self.shell.history_manager.get_range_by_str(arg)
266 histlines = self.shell.history_manager.get_range_by_str(arg)
267 cmd = "\n".join(x[2] for x in histlines)
267 cmd = "\n".join(x[2] for x in histlines)
268 if cmd:
268 if cmd:
269 self.shell.set_next_input(cmd.rstrip())
269 self.shell.set_next_input(cmd.rstrip())
270 return
270 return
271
271
272 try: # Variable in user namespace
272 try: # Variable in user namespace
273 cmd = str(eval(arg, self.shell.user_ns))
273 cmd = str(eval(arg, self.shell.user_ns))
274 except Exception: # Search for term in history
274 except Exception: # Search for term in history
275 histlines = self.shell.history_manager.search("*"+arg+"*")
275 histlines = self.shell.history_manager.search("*"+arg+"*")
276 for h in reversed([x[2] for x in histlines]):
276 for h in reversed([x[2] for x in histlines]):
277 if 'recall' in h or 'rep' in h:
277 if 'recall' in h or 'rep' in h:
278 continue
278 continue
279 self.shell.set_next_input(h.rstrip())
279 self.shell.set_next_input(h.rstrip())
280 return
280 return
281 else:
281 else:
282 self.shell.set_next_input(cmd.rstrip())
282 self.shell.set_next_input(cmd.rstrip())
283 return
283 return
284 print("Couldn't evaluate or find in history:", arg)
284 print("Couldn't evaluate or find in history:", arg)
285
285
286 @line_magic
286 @line_magic
287 def rerun(self, parameter_s=''):
287 def rerun(self, parameter_s=''):
288 """Re-run previous input
288 """Re-run previous input
289
289
290 By default, you can specify ranges of input history to be repeated
290 By default, you can specify ranges of input history to be repeated
291 (as with %history). With no arguments, it will repeat the last line.
291 (as with %history). With no arguments, it will repeat the last line.
292
292
293 Options:
293 Options:
294
294
295 -l <n> : Repeat the last n lines of input, not including the
295 -l <n> : Repeat the last n lines of input, not including the
296 current command.
296 current command.
297
297
298 -g foo : Repeat the most recent line which contains foo
298 -g foo : Repeat the most recent line which contains foo
299 """
299 """
300 opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
300 opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
301 if "l" in opts: # Last n lines
301 if "l" in opts: # Last n lines
302 try:
302 try:
303 n = int(opts["l"])
303 n = int(opts["l"])
304 except ValueError:
304 except ValueError:
305 print("Number of lines must be an integer")
305 print("Number of lines must be an integer")
306 return
306 return
307
307
308 if n == 0:
308 if n == 0:
309 print("Requested 0 last lines - nothing to run")
309 print("Requested 0 last lines - nothing to run")
310 return
310 return
311 elif n < 0:
311 elif n < 0:
312 print("Number of lines to rerun cannot be negative")
312 print("Number of lines to rerun cannot be negative")
313 return
313 return
314
314
315 hist = self.shell.history_manager.get_tail(n)
315 hist = self.shell.history_manager.get_tail(n)
316 elif "g" in opts: # Search
316 elif "g" in opts: # Search
317 p = "*"+opts['g']+"*"
317 p = "*"+opts['g']+"*"
318 hist = list(self.shell.history_manager.search(p))
318 hist = list(self.shell.history_manager.search(p))
319 for l in reversed(hist):
319 for l in reversed(hist):
320 if "rerun" not in l[2]:
320 if "rerun" not in l[2]:
321 hist = [l] # The last match which isn't a %rerun
321 hist = [l] # The last match which isn't a %rerun
322 break
322 break
323 else:
323 else:
324 hist = [] # No matches except %rerun
324 hist = [] # No matches except %rerun
325 elif args: # Specify history ranges
325 elif args: # Specify history ranges
326 hist = self.shell.history_manager.get_range_by_str(args)
326 hist = self.shell.history_manager.get_range_by_str(args)
327 else: # Last line
327 else: # Last line
328 hist = self.shell.history_manager.get_tail(1)
328 hist = self.shell.history_manager.get_tail(1)
329 hist = [x[2] for x in hist]
329 hist = [x[2] for x in hist]
330 if not hist:
330 if not hist:
331 print("No lines in history match specification")
331 print("No lines in history match specification")
332 return
332 return
333 histlines = "\n".join(hist)
333 histlines = "\n".join(hist)
334 print("=== Executing: ===")
334 print("=== Executing: ===")
335 print(histlines)
335 print(histlines)
336 print("=== Output: ===")
336 print("=== Output: ===")
337 self.shell.run_cell("\n".join(hist), store_history=False)
337 self.shell.run_cell("\n".join(hist), store_history=False)
@@ -1,712 +1,703 b''
1 """Implementation of namespace-related magic functions.
1 """Implementation of namespace-related 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
14
15 # Stdlib
15 # Stdlib
16 import gc
16 import gc
17 import re
17 import re
18 import sys
18 import sys
19
19
20 # Our own packages
20 # Our own packages
21 from IPython.core import page
21 from IPython.core import page
22 from IPython.core.error import StdinNotImplementedError, UsageError
22 from IPython.core.error import StdinNotImplementedError, UsageError
23 from IPython.core.magic import Magics, magics_class, line_magic
23 from IPython.core.magic import Magics, magics_class, line_magic
24 from IPython.testing.skipdoctest import skip_doctest
24 from IPython.testing.skipdoctest import skip_doctest
25 from IPython.utils.encoding import DEFAULT_ENCODING
25 from IPython.utils.encoding import DEFAULT_ENCODING
26 from IPython.utils.openpy import read_py_file
26 from IPython.utils.openpy import read_py_file
27 from IPython.utils.path import get_py_filename
27 from IPython.utils.path import get_py_filename
28
28
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30 # Magic implementation classes
30 # Magic implementation classes
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32
32
33 @magics_class
33 @magics_class
34 class NamespaceMagics(Magics):
34 class NamespaceMagics(Magics):
35 """Magics to manage various aspects of the user's namespace.
35 """Magics to manage various aspects of the user's namespace.
36
36
37 These include listing variables, introspecting into them, etc.
37 These include listing variables, introspecting into them, etc.
38 """
38 """
39
39
40 @line_magic
40 @line_magic
41 def pinfo(self, parameter_s='', namespaces=None):
41 def pinfo(self, parameter_s='', namespaces=None):
42 """Provide detailed information about an object.
42 """Provide detailed information about an object.
43
43
44 '%pinfo object' is just a synonym for object? or ?object."""
44 '%pinfo object' is just a synonym for object? or ?object."""
45
45
46 #print 'pinfo par: <%s>' % parameter_s # dbg
46 #print 'pinfo par: <%s>' % parameter_s # dbg
47 # detail_level: 0 -> obj? , 1 -> obj??
47 # detail_level: 0 -> obj? , 1 -> obj??
48 detail_level = 0
48 detail_level = 0
49 # We need to detect if we got called as 'pinfo pinfo foo', which can
49 # We need to detect if we got called as 'pinfo pinfo foo', which can
50 # happen if the user types 'pinfo foo?' at the cmd line.
50 # happen if the user types 'pinfo foo?' at the cmd line.
51 pinfo,qmark1,oname,qmark2 = \
51 pinfo,qmark1,oname,qmark2 = \
52 re.match(r'(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
52 re.match(r'(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
53 if pinfo or qmark1 or qmark2:
53 if pinfo or qmark1 or qmark2:
54 detail_level = 1
54 detail_level = 1
55 if "*" in oname:
55 if "*" in oname:
56 self.psearch(oname)
56 self.psearch(oname)
57 else:
57 else:
58 self.shell._inspect('pinfo', oname, detail_level=detail_level,
58 self.shell._inspect('pinfo', oname, detail_level=detail_level,
59 namespaces=namespaces)
59 namespaces=namespaces)
60
60
61 @line_magic
61 @line_magic
62 def pinfo2(self, parameter_s='', namespaces=None):
62 def pinfo2(self, parameter_s='', namespaces=None):
63 """Provide extra detailed information about an object.
63 """Provide extra detailed information about an object.
64
64
65 '%pinfo2 object' is just a synonym for object?? or ??object."""
65 '%pinfo2 object' is just a synonym for object?? or ??object."""
66 self.shell._inspect('pinfo', parameter_s, detail_level=1,
66 self.shell._inspect('pinfo', parameter_s, detail_level=1,
67 namespaces=namespaces)
67 namespaces=namespaces)
68
68
69 @skip_doctest
69 @skip_doctest
70 @line_magic
70 @line_magic
71 def pdef(self, parameter_s='', namespaces=None):
71 def pdef(self, parameter_s='', namespaces=None):
72 """Print the call signature for any callable object.
72 """Print the call signature for any callable object.
73
73
74 If the object is a class, print the constructor information.
74 If the object is a class, print the constructor information.
75
75
76 Examples
76 Examples
77 --------
77 --------
78 ::
78 ::
79
79
80 In [3]: %pdef urllib.urlopen
80 In [3]: %pdef urllib.urlopen
81 urllib.urlopen(url, data=None, proxies=None)
81 urllib.urlopen(url, data=None, proxies=None)
82 """
82 """
83 self.shell._inspect('pdef',parameter_s, namespaces)
83 self.shell._inspect('pdef',parameter_s, namespaces)
84
84
85 @line_magic
85 @line_magic
86 def pdoc(self, parameter_s='', namespaces=None):
86 def pdoc(self, parameter_s='', namespaces=None):
87 """Print the docstring for an object.
87 """Print the docstring for an object.
88
88
89 If the given object is a class, it will print both the class and the
89 If the given object is a class, it will print both the class and the
90 constructor docstrings."""
90 constructor docstrings."""
91 self.shell._inspect('pdoc',parameter_s, namespaces)
91 self.shell._inspect('pdoc',parameter_s, namespaces)
92
92
93 @line_magic
93 @line_magic
94 def psource(self, parameter_s='', namespaces=None):
94 def psource(self, parameter_s='', namespaces=None):
95 """Print (or run through pager) the source code for an object."""
95 """Print (or run through pager) the source code for an object."""
96 if not parameter_s:
96 if not parameter_s:
97 raise UsageError('Missing object name.')
97 raise UsageError('Missing object name.')
98 self.shell._inspect('psource',parameter_s, namespaces)
98 self.shell._inspect('psource',parameter_s, namespaces)
99
99
100 @line_magic
100 @line_magic
101 def pfile(self, parameter_s='', namespaces=None):
101 def pfile(self, parameter_s='', namespaces=None):
102 """Print (or run through pager) the file where an object is defined.
102 """Print (or run through pager) the file where an object is defined.
103
103
104 The file opens at the line where the object definition begins. IPython
104 The file opens at the line where the object definition begins. IPython
105 will honor the environment variable PAGER if set, and otherwise will
105 will honor the environment variable PAGER if set, and otherwise will
106 do its best to print the file in a convenient form.
106 do its best to print the file in a convenient form.
107
107
108 If the given argument is not an object currently defined, IPython will
108 If the given argument is not an object currently defined, IPython will
109 try to interpret it as a filename (automatically adding a .py extension
109 try to interpret it as a filename (automatically adding a .py extension
110 if needed). You can thus use %pfile as a syntax highlighting code
110 if needed). You can thus use %pfile as a syntax highlighting code
111 viewer."""
111 viewer."""
112
112
113 # first interpret argument as an object name
113 # first interpret argument as an object name
114 out = self.shell._inspect('pfile',parameter_s, namespaces)
114 out = self.shell._inspect('pfile',parameter_s, namespaces)
115 # if not, try the input as a filename
115 # if not, try the input as a filename
116 if out == 'not found':
116 if out == 'not found':
117 try:
117 try:
118 filename = get_py_filename(parameter_s)
118 filename = get_py_filename(parameter_s)
119 except IOError as msg:
119 except IOError as msg:
120 print(msg)
120 print(msg)
121 return
121 return
122 page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False)))
122 page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False)))
123
123
124 @line_magic
124 @line_magic
125 def psearch(self, parameter_s=''):
125 def psearch(self, parameter_s=''):
126 """Search for object in namespaces by wildcard.
126 """Search for object in namespaces by wildcard.
127
127
128 %psearch [options] PATTERN [OBJECT TYPE]
128 %psearch [options] PATTERN [OBJECT TYPE]
129
129
130 Note: ? can be used as a synonym for %psearch, at the beginning or at
130 Note: ? can be used as a synonym for %psearch, at the beginning or at
131 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
131 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
132 rest of the command line must be unchanged (options come first), so
132 rest of the command line must be unchanged (options come first), so
133 for example the following forms are equivalent
133 for example the following forms are equivalent
134
134
135 %psearch -i a* function
135 %psearch -i a* function
136 -i a* function?
136 -i a* function?
137 ?-i a* function
137 ?-i a* function
138
138
139 Arguments:
139 Arguments:
140
140
141 PATTERN
141 PATTERN
142
142
143 where PATTERN is a string containing * as a wildcard similar to its
143 where PATTERN is a string containing * as a wildcard similar to its
144 use in a shell. The pattern is matched in all namespaces on the
144 use in a shell. The pattern is matched in all namespaces on the
145 search path. By default objects starting with a single _ are not
145 search path. By default objects starting with a single _ are not
146 matched, many IPython generated objects have a single
146 matched, many IPython generated objects have a single
147 underscore. The default is case insensitive matching. Matching is
147 underscore. The default is case insensitive matching. Matching is
148 also done on the attributes of objects and not only on the objects
148 also done on the attributes of objects and not only on the objects
149 in a module.
149 in a module.
150
150
151 [OBJECT TYPE]
151 [OBJECT TYPE]
152
152
153 Is the name of a python type from the types module. The name is
153 Is the name of a python type from the types module. The name is
154 given in lowercase without the ending type, ex. StringType is
154 given in lowercase without the ending type, ex. StringType is
155 written string. By adding a type here only objects matching the
155 written string. By adding a type here only objects matching the
156 given type are matched. Using all here makes the pattern match all
156 given type are matched. Using all here makes the pattern match all
157 types (this is the default).
157 types (this is the default).
158
158
159 Options:
159 Options:
160
160
161 -a: makes the pattern match even objects whose names start with a
161 -a: makes the pattern match even objects whose names start with a
162 single underscore. These names are normally omitted from the
162 single underscore. These names are normally omitted from the
163 search.
163 search.
164
164
165 -i/-c: make the pattern case insensitive/sensitive. If neither of
165 -i/-c: make the pattern case insensitive/sensitive. If neither of
166 these options are given, the default is read from your configuration
166 these options are given, the default is read from your configuration
167 file, with the option ``InteractiveShell.wildcards_case_sensitive``.
167 file, with the option ``InteractiveShell.wildcards_case_sensitive``.
168 If this option is not specified in your configuration file, IPython's
168 If this option is not specified in your configuration file, IPython's
169 internal default is to do a case sensitive search.
169 internal default is to do a case sensitive search.
170
170
171 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
171 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
172 specify can be searched in any of the following namespaces:
172 specify can be searched in any of the following namespaces:
173 'builtin', 'user', 'user_global','internal', 'alias', where
173 'builtin', 'user', 'user_global','internal', 'alias', where
174 'builtin' and 'user' are the search defaults. Note that you should
174 'builtin' and 'user' are the search defaults. Note that you should
175 not use quotes when specifying namespaces.
175 not use quotes when specifying namespaces.
176
176
177 -l: List all available object types for object matching. This function
177 -l: List all available object types for object matching. This function
178 can be used without arguments.
178 can be used without arguments.
179
179
180 'Builtin' contains the python module builtin, 'user' contains all
180 'Builtin' contains the python module builtin, 'user' contains all
181 user data, 'alias' only contain the shell aliases and no python
181 user data, 'alias' only contain the shell aliases and no python
182 objects, 'internal' contains objects used by IPython. The
182 objects, 'internal' contains objects used by IPython. The
183 'user_global' namespace is only used by embedded IPython instances,
183 'user_global' namespace is only used by embedded IPython instances,
184 and it contains module-level globals. You can add namespaces to the
184 and it contains module-level globals. You can add namespaces to the
185 search with -s or exclude them with -e (these options can be given
185 search with -s or exclude them with -e (these options can be given
186 more than once).
186 more than once).
187
187
188 Examples
188 Examples
189 --------
189 --------
190 ::
190 ::
191
191
192 %psearch a* -> objects beginning with an a
192 %psearch a* -> objects beginning with an a
193 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
193 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
194 %psearch a* function -> all functions beginning with an a
194 %psearch a* function -> all functions beginning with an a
195 %psearch re.e* -> objects beginning with an e in module re
195 %psearch re.e* -> objects beginning with an e in module re
196 %psearch r*.e* -> objects that start with e in modules starting in r
196 %psearch r*.e* -> objects that start with e in modules starting in r
197 %psearch r*.* string -> all strings in modules beginning with r
197 %psearch r*.* string -> all strings in modules beginning with r
198
198
199 Case sensitive search::
199 Case sensitive search::
200
200
201 %psearch -c a* list all object beginning with lower case a
201 %psearch -c a* list all object beginning with lower case a
202
202
203 Show objects beginning with a single _::
203 Show objects beginning with a single _::
204
204
205 %psearch -a _* list objects beginning with a single underscore
205 %psearch -a _* list objects beginning with a single underscore
206
206
207 List available objects::
207 List available objects::
208
208
209 %psearch -l list all available object types
209 %psearch -l list all available object types
210 """
210 """
211 # default namespaces to be searched
211 # default namespaces to be searched
212 def_search = ['user_local', 'user_global', 'builtin']
212 def_search = ['user_local', 'user_global', 'builtin']
213
213
214 # Process options/args
214 # Process options/args
215 opts,args = self.parse_options(parameter_s,'cias:e:l',list_all=True)
215 opts,args = self.parse_options(parameter_s,'cias:e:l',list_all=True)
216 opt = opts.get
216 opt = opts.get
217 shell = self.shell
217 shell = self.shell
218 psearch = shell.inspector.psearch
218 psearch = shell.inspector.psearch
219
219
220 # select list object types
220 # select list object types
221 list_types = False
221 list_types = False
222 if 'l' in opts:
222 if 'l' in opts:
223 list_types = True
223 list_types = True
224
224
225 # select case options
225 # select case options
226 if 'i' in opts:
226 if 'i' in opts:
227 ignore_case = True
227 ignore_case = True
228 elif 'c' in opts:
228 elif 'c' in opts:
229 ignore_case = False
229 ignore_case = False
230 else:
230 else:
231 ignore_case = not shell.wildcards_case_sensitive
231 ignore_case = not shell.wildcards_case_sensitive
232
232
233 # Build list of namespaces to search from user options
233 # Build list of namespaces to search from user options
234 def_search.extend(opt('s',[]))
234 def_search.extend(opt('s',[]))
235 ns_exclude = ns_exclude=opt('e',[])
235 ns_exclude = ns_exclude=opt('e',[])
236 ns_search = [nm for nm in def_search if nm not in ns_exclude]
236 ns_search = [nm for nm in def_search if nm not in ns_exclude]
237
237
238 # Call the actual search
238 # Call the actual search
239 try:
239 try:
240 psearch(args,shell.ns_table,ns_search,
240 psearch(args,shell.ns_table,ns_search,
241 show_all=opt('a'),ignore_case=ignore_case, list_types=list_types)
241 show_all=opt('a'),ignore_case=ignore_case, list_types=list_types)
242 except:
242 except:
243 shell.showtraceback()
243 shell.showtraceback()
244
244
245 @skip_doctest
245 @skip_doctest
246 @line_magic
246 @line_magic
247 def who_ls(self, parameter_s=''):
247 def who_ls(self, parameter_s=''):
248 """Return a sorted list of all interactive variables.
248 """Return a sorted list of all interactive variables.
249
249
250 If arguments are given, only variables of types matching these
250 If arguments are given, only variables of types matching these
251 arguments are returned.
251 arguments are returned.
252
252
253 Examples
253 Examples
254 --------
254 --------
255
256 Define two variables and list them with who_ls::
255 Define two variables and list them with who_ls::
257
256
258 In [1]: alpha = 123
257 In [1]: alpha = 123
259
258
260 In [2]: beta = 'test'
259 In [2]: beta = 'test'
261
260
262 In [3]: %who_ls
261 In [3]: %who_ls
263 Out[3]: ['alpha', 'beta']
262 Out[3]: ['alpha', 'beta']
264
263
265 In [4]: %who_ls int
264 In [4]: %who_ls int
266 Out[4]: ['alpha']
265 Out[4]: ['alpha']
267
266
268 In [5]: %who_ls str
267 In [5]: %who_ls str
269 Out[5]: ['beta']
268 Out[5]: ['beta']
270 """
269 """
271
270
272 user_ns = self.shell.user_ns
271 user_ns = self.shell.user_ns
273 user_ns_hidden = self.shell.user_ns_hidden
272 user_ns_hidden = self.shell.user_ns_hidden
274 nonmatching = object() # This can never be in user_ns
273 nonmatching = object() # This can never be in user_ns
275 out = [ i for i in user_ns
274 out = [ i for i in user_ns
276 if not i.startswith('_') \
275 if not i.startswith('_') \
277 and (user_ns[i] is not user_ns_hidden.get(i, nonmatching)) ]
276 and (user_ns[i] is not user_ns_hidden.get(i, nonmatching)) ]
278
277
279 typelist = parameter_s.split()
278 typelist = parameter_s.split()
280 if typelist:
279 if typelist:
281 typeset = set(typelist)
280 typeset = set(typelist)
282 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
281 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
283
282
284 out.sort()
283 out.sort()
285 return out
284 return out
286
285
287 @skip_doctest
286 @skip_doctest
288 @line_magic
287 @line_magic
289 def who(self, parameter_s=''):
288 def who(self, parameter_s=''):
290 """Print all interactive variables, with some minimal formatting.
289 """Print all interactive variables, with some minimal formatting.
291
290
292 If any arguments are given, only variables whose type matches one of
291 If any arguments are given, only variables whose type matches one of
293 these are printed. For example::
292 these are printed. For example::
294
293
295 %who function str
294 %who function str
296
295
297 will only list functions and strings, excluding all other types of
296 will only list functions and strings, excluding all other types of
298 variables. To find the proper type names, simply use type(var) at a
297 variables. To find the proper type names, simply use type(var) at a
299 command line to see how python prints type names. For example:
298 command line to see how python prints type names. For example:
300
299
301 ::
300 ::
302
301
303 In [1]: type('hello')\\
302 In [1]: type('hello')\\
304 Out[1]: <type 'str'>
303 Out[1]: <type 'str'>
305
304
306 indicates that the type name for strings is 'str'.
305 indicates that the type name for strings is 'str'.
307
306
308 ``%who`` always excludes executed names loaded through your configuration
307 ``%who`` always excludes executed names loaded through your configuration
309 file and things which are internal to IPython.
308 file and things which are internal to IPython.
310
309
311 This is deliberate, as typically you may load many modules and the
310 This is deliberate, as typically you may load many modules and the
312 purpose of %who is to show you only what you've manually defined.
311 purpose of %who is to show you only what you've manually defined.
313
312
314 Examples
313 Examples
315 --------
314 --------
316
315
317 Define two variables and list them with who::
316 Define two variables and list them with who::
318
317
319 In [1]: alpha = 123
318 In [1]: alpha = 123
320
319
321 In [2]: beta = 'test'
320 In [2]: beta = 'test'
322
321
323 In [3]: %who
322 In [3]: %who
324 alpha beta
323 alpha beta
325
324
326 In [4]: %who int
325 In [4]: %who int
327 alpha
326 alpha
328
327
329 In [5]: %who str
328 In [5]: %who str
330 beta
329 beta
331 """
330 """
332
331
333 varlist = self.who_ls(parameter_s)
332 varlist = self.who_ls(parameter_s)
334 if not varlist:
333 if not varlist:
335 if parameter_s:
334 if parameter_s:
336 print('No variables match your requested type.')
335 print('No variables match your requested type.')
337 else:
336 else:
338 print('Interactive namespace is empty.')
337 print('Interactive namespace is empty.')
339 return
338 return
340
339
341 # if we have variables, move on...
340 # if we have variables, move on...
342 count = 0
341 count = 0
343 for i in varlist:
342 for i in varlist:
344 print(i+'\t', end=' ')
343 print(i+'\t', end=' ')
345 count += 1
344 count += 1
346 if count > 8:
345 if count > 8:
347 count = 0
346 count = 0
348 print()
347 print()
349 print()
348 print()
350
349
351 @skip_doctest
350 @skip_doctest
352 @line_magic
351 @line_magic
353 def whos(self, parameter_s=''):
352 def whos(self, parameter_s=''):
354 """Like %who, but gives some extra information about each variable.
353 """Like %who, but gives some extra information about each variable.
355
354
356 The same type filtering of %who can be applied here.
355 The same type filtering of %who can be applied here.
357
356
358 For all variables, the type is printed. Additionally it prints:
357 For all variables, the type is printed. Additionally it prints:
359
358
360 - For {},[],(): their length.
359 - For {},[],(): their length.
361
360
362 - For numpy arrays, a summary with shape, number of
361 - For numpy arrays, a summary with shape, number of
363 elements, typecode and size in memory.
362 elements, typecode and size in memory.
364
363
365 - Everything else: a string representation, snipping their middle if
364 - Everything else: a string representation, snipping their middle if
366 too long.
365 too long.
367
366
368 Examples
367 Examples
369 --------
368 --------
370
371 Define two variables and list them with whos::
369 Define two variables and list them with whos::
372
370
373 In [1]: alpha = 123
371 In [1]: alpha = 123
374
372
375 In [2]: beta = 'test'
373 In [2]: beta = 'test'
376
374
377 In [3]: %whos
375 In [3]: %whos
378 Variable Type Data/Info
376 Variable Type Data/Info
379 --------------------------------
377 --------------------------------
380 alpha int 123
378 alpha int 123
381 beta str test
379 beta str test
382 """
380 """
383
381
384 varnames = self.who_ls(parameter_s)
382 varnames = self.who_ls(parameter_s)
385 if not varnames:
383 if not varnames:
386 if parameter_s:
384 if parameter_s:
387 print('No variables match your requested type.')
385 print('No variables match your requested type.')
388 else:
386 else:
389 print('Interactive namespace is empty.')
387 print('Interactive namespace is empty.')
390 return
388 return
391
389
392 # if we have variables, move on...
390 # if we have variables, move on...
393
391
394 # for these types, show len() instead of data:
392 # for these types, show len() instead of data:
395 seq_types = ['dict', 'list', 'tuple']
393 seq_types = ['dict', 'list', 'tuple']
396
394
397 # for numpy arrays, display summary info
395 # for numpy arrays, display summary info
398 ndarray_type = None
396 ndarray_type = None
399 if 'numpy' in sys.modules:
397 if 'numpy' in sys.modules:
400 try:
398 try:
401 from numpy import ndarray
399 from numpy import ndarray
402 except ImportError:
400 except ImportError:
403 pass
401 pass
404 else:
402 else:
405 ndarray_type = ndarray.__name__
403 ndarray_type = ndarray.__name__
406
404
407 # Find all variable names and types so we can figure out column sizes
405 # Find all variable names and types so we can figure out column sizes
408
406
409 # some types are well known and can be shorter
407 # some types are well known and can be shorter
410 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
408 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
411 def type_name(v):
409 def type_name(v):
412 tn = type(v).__name__
410 tn = type(v).__name__
413 return abbrevs.get(tn,tn)
411 return abbrevs.get(tn,tn)
414
412
415 varlist = [self.shell.user_ns[n] for n in varnames]
413 varlist = [self.shell.user_ns[n] for n in varnames]
416
414
417 typelist = []
415 typelist = []
418 for vv in varlist:
416 for vv in varlist:
419 tt = type_name(vv)
417 tt = type_name(vv)
420
418
421 if tt=='instance':
419 if tt=='instance':
422 typelist.append( abbrevs.get(str(vv.__class__),
420 typelist.append( abbrevs.get(str(vv.__class__),
423 str(vv.__class__)))
421 str(vv.__class__)))
424 else:
422 else:
425 typelist.append(tt)
423 typelist.append(tt)
426
424
427 # column labels and # of spaces as separator
425 # column labels and # of spaces as separator
428 varlabel = 'Variable'
426 varlabel = 'Variable'
429 typelabel = 'Type'
427 typelabel = 'Type'
430 datalabel = 'Data/Info'
428 datalabel = 'Data/Info'
431 colsep = 3
429 colsep = 3
432 # variable format strings
430 # variable format strings
433 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
431 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
434 aformat = "%s: %s elems, type `%s`, %s bytes"
432 aformat = "%s: %s elems, type `%s`, %s bytes"
435 # find the size of the columns to format the output nicely
433 # find the size of the columns to format the output nicely
436 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
434 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
437 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
435 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
438 # table header
436 # table header
439 print(varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
437 print(varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
440 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1))
438 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1))
441 # and the table itself
439 # and the table itself
442 kb = 1024
440 kb = 1024
443 Mb = 1048576 # kb**2
441 Mb = 1048576 # kb**2
444 for vname,var,vtype in zip(varnames,varlist,typelist):
442 for vname,var,vtype in zip(varnames,varlist,typelist):
445 print(vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), end=' ')
443 print(vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), end=' ')
446 if vtype in seq_types:
444 if vtype in seq_types:
447 print("n="+str(len(var)))
445 print("n="+str(len(var)))
448 elif vtype == ndarray_type:
446 elif vtype == ndarray_type:
449 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
447 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
450 if vtype==ndarray_type:
448 if vtype==ndarray_type:
451 # numpy
449 # numpy
452 vsize = var.size
450 vsize = var.size
453 vbytes = vsize*var.itemsize
451 vbytes = vsize*var.itemsize
454 vdtype = var.dtype
452 vdtype = var.dtype
455
453
456 if vbytes < 100000:
454 if vbytes < 100000:
457 print(aformat % (vshape, vsize, vdtype, vbytes))
455 print(aformat % (vshape, vsize, vdtype, vbytes))
458 else:
456 else:
459 print(aformat % (vshape, vsize, vdtype, vbytes), end=' ')
457 print(aformat % (vshape, vsize, vdtype, vbytes), end=' ')
460 if vbytes < Mb:
458 if vbytes < Mb:
461 print('(%s kb)' % (vbytes/kb,))
459 print('(%s kb)' % (vbytes/kb,))
462 else:
460 else:
463 print('(%s Mb)' % (vbytes/Mb,))
461 print('(%s Mb)' % (vbytes/Mb,))
464 else:
462 else:
465 try:
463 try:
466 vstr = str(var)
464 vstr = str(var)
467 except UnicodeEncodeError:
465 except UnicodeEncodeError:
468 vstr = var.encode(DEFAULT_ENCODING,
466 vstr = var.encode(DEFAULT_ENCODING,
469 'backslashreplace')
467 'backslashreplace')
470 except:
468 except:
471 vstr = "<object with id %d (str() failed)>" % id(var)
469 vstr = "<object with id %d (str() failed)>" % id(var)
472 vstr = vstr.replace('\n', '\\n')
470 vstr = vstr.replace('\n', '\\n')
473 if len(vstr) < 50:
471 if len(vstr) < 50:
474 print(vstr)
472 print(vstr)
475 else:
473 else:
476 print(vstr[:25] + "<...>" + vstr[-25:])
474 print(vstr[:25] + "<...>" + vstr[-25:])
477
475
478 @line_magic
476 @line_magic
479 def reset(self, parameter_s=''):
477 def reset(self, parameter_s=''):
480 """Resets the namespace by removing all names defined by the user, if
478 """Resets the namespace by removing all names defined by the user, if
481 called without arguments, or by removing some types of objects, such
479 called without arguments, or by removing some types of objects, such
482 as everything currently in IPython's In[] and Out[] containers (see
480 as everything currently in IPython's In[] and Out[] containers (see
483 the parameters for details).
481 the parameters for details).
484
482
485 Parameters
483 Parameters
486 ----------
484 ----------
487 -f : force reset without asking for confirmation.
485 -f : force reset without asking for confirmation.
488
489 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
486 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
490 References to objects may be kept. By default (without this option),
487 References to objects may be kept. By default (without this option),
491 we do a 'hard' reset, giving you a new session and removing all
488 we do a 'hard' reset, giving you a new session and removing all
492 references to objects from the current session.
489 references to objects from the current session.
493
490 --aggressive : Try to aggressively remove modules from sys.modules ; this
494 --aggressive: Try to aggressively remove modules from sys.modules ; this
495 may allow you to reimport Python modules that have been updated and
491 may allow you to reimport Python modules that have been updated and
496 pick up changes, but can have unattended consequences.
492 pick up changes, but can have unattended consequences.
497
498 in : reset input history
493 in : reset input history
499
500 out : reset output history
494 out : reset output history
501
502 dhist : reset directory history
495 dhist : reset directory history
503
504 array : reset only variables that are NumPy arrays
496 array : reset only variables that are NumPy arrays
505
497
506 See Also
498 See Also
507 --------
499 --------
508 reset_selective : invoked as ``%reset_selective``
500 reset_selective : invoked as ``%reset_selective``
509
501
510 Examples
502 Examples
511 --------
503 --------
512 ::
504 ::
513
505
514 In [6]: a = 1
506 In [6]: a = 1
515
507
516 In [7]: a
508 In [7]: a
517 Out[7]: 1
509 Out[7]: 1
518
510
519 In [8]: 'a' in get_ipython().user_ns
511 In [8]: 'a' in get_ipython().user_ns
520 Out[8]: True
512 Out[8]: True
521
513
522 In [9]: %reset -f
514 In [9]: %reset -f
523
515
524 In [1]: 'a' in get_ipython().user_ns
516 In [1]: 'a' in get_ipython().user_ns
525 Out[1]: False
517 Out[1]: False
526
518
527 In [2]: %reset -f in
519 In [2]: %reset -f in
528 Flushing input history
520 Flushing input history
529
521
530 In [3]: %reset -f dhist in
522 In [3]: %reset -f dhist in
531 Flushing directory history
523 Flushing directory history
532 Flushing input history
524 Flushing input history
533
525
534 Notes
526 Notes
535 -----
527 -----
536 Calling this magic from clients that do not implement standard input,
528 Calling this magic from clients that do not implement standard input,
537 such as the ipython notebook interface, will reset the namespace
529 such as the ipython notebook interface, will reset the namespace
538 without confirmation.
530 without confirmation.
539 """
531 """
540 opts, args = self.parse_options(parameter_s, "sf", "aggressive", mode="list")
532 opts, args = self.parse_options(parameter_s, "sf", "aggressive", mode="list")
541 if "f" in opts:
533 if "f" in opts:
542 ans = True
534 ans = True
543 else:
535 else:
544 try:
536 try:
545 ans = self.shell.ask_yes_no(
537 ans = self.shell.ask_yes_no(
546 "Once deleted, variables cannot be recovered. Proceed (y/[n])?",
538 "Once deleted, variables cannot be recovered. Proceed (y/[n])?",
547 default='n')
539 default='n')
548 except StdinNotImplementedError:
540 except StdinNotImplementedError:
549 ans = True
541 ans = True
550 if not ans:
542 if not ans:
551 print('Nothing done.')
543 print('Nothing done.')
552 return
544 return
553
545
554 if 's' in opts: # Soft reset
546 if 's' in opts: # Soft reset
555 user_ns = self.shell.user_ns
547 user_ns = self.shell.user_ns
556 for i in self.who_ls():
548 for i in self.who_ls():
557 del(user_ns[i])
549 del(user_ns[i])
558 elif len(args) == 0: # Hard reset
550 elif len(args) == 0: # Hard reset
559 self.shell.reset(new_session=False, aggressive=("aggressive" in opts))
551 self.shell.reset(new_session=False, aggressive=("aggressive" in opts))
560
552
561 # reset in/out/dhist/array: previously extensinions/clearcmd.py
553 # reset in/out/dhist/array: previously extensinions/clearcmd.py
562 ip = self.shell
554 ip = self.shell
563 user_ns = self.shell.user_ns # local lookup, heavily used
555 user_ns = self.shell.user_ns # local lookup, heavily used
564
556
565 for target in args:
557 for target in args:
566 target = target.lower() # make matches case insensitive
558 target = target.lower() # make matches case insensitive
567 if target == 'out':
559 if target == 'out':
568 print("Flushing output cache (%d entries)" % len(user_ns['_oh']))
560 print("Flushing output cache (%d entries)" % len(user_ns['_oh']))
569 self.shell.displayhook.flush()
561 self.shell.displayhook.flush()
570
562
571 elif target == 'in':
563 elif target == 'in':
572 print("Flushing input history")
564 print("Flushing input history")
573 pc = self.shell.displayhook.prompt_count + 1
565 pc = self.shell.displayhook.prompt_count + 1
574 for n in range(1, pc):
566 for n in range(1, pc):
575 key = '_i'+repr(n)
567 key = '_i'+repr(n)
576 user_ns.pop(key,None)
568 user_ns.pop(key,None)
577 user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
569 user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
578 hm = ip.history_manager
570 hm = ip.history_manager
579 # don't delete these, as %save and %macro depending on the
571 # don't delete these, as %save and %macro depending on the
580 # length of these lists to be preserved
572 # length of these lists to be preserved
581 hm.input_hist_parsed[:] = [''] * pc
573 hm.input_hist_parsed[:] = [''] * pc
582 hm.input_hist_raw[:] = [''] * pc
574 hm.input_hist_raw[:] = [''] * pc
583 # hm has internal machinery for _i,_ii,_iii, clear it out
575 # hm has internal machinery for _i,_ii,_iii, clear it out
584 hm._i = hm._ii = hm._iii = hm._i00 = u''
576 hm._i = hm._ii = hm._iii = hm._i00 = u''
585
577
586 elif target == 'array':
578 elif target == 'array':
587 # Support cleaning up numpy arrays
579 # Support cleaning up numpy arrays
588 try:
580 try:
589 from numpy import ndarray
581 from numpy import ndarray
590 # This must be done with items and not iteritems because
582 # This must be done with items and not iteritems because
591 # we're going to modify the dict in-place.
583 # we're going to modify the dict in-place.
592 for x,val in list(user_ns.items()):
584 for x,val in list(user_ns.items()):
593 if isinstance(val,ndarray):
585 if isinstance(val,ndarray):
594 del user_ns[x]
586 del user_ns[x]
595 except ImportError:
587 except ImportError:
596 print("reset array only works if Numpy is available.")
588 print("reset array only works if Numpy is available.")
597
589
598 elif target == 'dhist':
590 elif target == 'dhist':
599 print("Flushing directory history")
591 print("Flushing directory history")
600 del user_ns['_dh'][:]
592 del user_ns['_dh'][:]
601
593
602 else:
594 else:
603 print("Don't know how to reset ", end=' ')
595 print("Don't know how to reset ", end=' ')
604 print(target + ", please run `%reset?` for details")
596 print(target + ", please run `%reset?` for details")
605
597
606 gc.collect()
598 gc.collect()
607
599
608 @line_magic
600 @line_magic
609 def reset_selective(self, parameter_s=''):
601 def reset_selective(self, parameter_s=''):
610 """Resets the namespace by removing names defined by the user.
602 """Resets the namespace by removing names defined by the user.
611
603
612 Input/Output history are left around in case you need them.
604 Input/Output history are left around in case you need them.
613
605
614 %reset_selective [-f] regex
606 %reset_selective [-f] regex
615
607
616 No action is taken if regex is not included
608 No action is taken if regex is not included
617
609
618 Options
610 Options
619 -f : force reset without asking for confirmation.
611 -f : force reset without asking for confirmation.
620
612
621 See Also
613 See Also
622 --------
614 --------
623 reset : invoked as ``%reset``
615 reset : invoked as ``%reset``
624
616
625 Examples
617 Examples
626 --------
618 --------
627
628 We first fully reset the namespace so your output looks identical to
619 We first fully reset the namespace so your output looks identical to
629 this example for pedagogical reasons; in practice you do not need a
620 this example for pedagogical reasons; in practice you do not need a
630 full reset::
621 full reset::
631
622
632 In [1]: %reset -f
623 In [1]: %reset -f
633
624
634 Now, with a clean namespace we can make a few variables and use
625 Now, with a clean namespace we can make a few variables and use
635 ``%reset_selective`` to only delete names that match our regexp::
626 ``%reset_selective`` to only delete names that match our regexp::
636
627
637 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
628 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
638
629
639 In [3]: who_ls
630 In [3]: who_ls
640 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
631 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
641
632
642 In [4]: %reset_selective -f b[2-3]m
633 In [4]: %reset_selective -f b[2-3]m
643
634
644 In [5]: who_ls
635 In [5]: who_ls
645 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
636 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
646
637
647 In [6]: %reset_selective -f d
638 In [6]: %reset_selective -f d
648
639
649 In [7]: who_ls
640 In [7]: who_ls
650 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
641 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
651
642
652 In [8]: %reset_selective -f c
643 In [8]: %reset_selective -f c
653
644
654 In [9]: who_ls
645 In [9]: who_ls
655 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
646 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
656
647
657 In [10]: %reset_selective -f b
648 In [10]: %reset_selective -f b
658
649
659 In [11]: who_ls
650 In [11]: who_ls
660 Out[11]: ['a']
651 Out[11]: ['a']
661
652
662 Notes
653 Notes
663 -----
654 -----
664 Calling this magic from clients that do not implement standard input,
655 Calling this magic from clients that do not implement standard input,
665 such as the ipython notebook interface, will reset the namespace
656 such as the ipython notebook interface, will reset the namespace
666 without confirmation.
657 without confirmation.
667 """
658 """
668
659
669 opts, regex = self.parse_options(parameter_s,'f')
660 opts, regex = self.parse_options(parameter_s,'f')
670
661
671 if 'f' in opts:
662 if 'f' in opts:
672 ans = True
663 ans = True
673 else:
664 else:
674 try:
665 try:
675 ans = self.shell.ask_yes_no(
666 ans = self.shell.ask_yes_no(
676 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
667 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
677 default='n')
668 default='n')
678 except StdinNotImplementedError:
669 except StdinNotImplementedError:
679 ans = True
670 ans = True
680 if not ans:
671 if not ans:
681 print('Nothing done.')
672 print('Nothing done.')
682 return
673 return
683 user_ns = self.shell.user_ns
674 user_ns = self.shell.user_ns
684 if not regex:
675 if not regex:
685 print('No regex pattern specified. Nothing done.')
676 print('No regex pattern specified. Nothing done.')
686 return
677 return
687 else:
678 else:
688 try:
679 try:
689 m = re.compile(regex)
680 m = re.compile(regex)
690 except TypeError as e:
681 except TypeError as e:
691 raise TypeError('regex must be a string or compiled pattern') from e
682 raise TypeError('regex must be a string or compiled pattern') from e
692 for i in self.who_ls():
683 for i in self.who_ls():
693 if m.search(i):
684 if m.search(i):
694 del(user_ns[i])
685 del(user_ns[i])
695
686
696 @line_magic
687 @line_magic
697 def xdel(self, parameter_s=''):
688 def xdel(self, parameter_s=''):
698 """Delete a variable, trying to clear it from anywhere that
689 """Delete a variable, trying to clear it from anywhere that
699 IPython's machinery has references to it. By default, this uses
690 IPython's machinery has references to it. By default, this uses
700 the identity of the named object in the user namespace to remove
691 the identity of the named object in the user namespace to remove
701 references held under other names. The object is also removed
692 references held under other names. The object is also removed
702 from the output history.
693 from the output history.
703
694
704 Options
695 Options
705 -n : Delete the specified name from all namespaces, without
696 -n : Delete the specified name from all namespaces, without
706 checking their identity.
697 checking their identity.
707 """
698 """
708 opts, varname = self.parse_options(parameter_s,'n')
699 opts, varname = self.parse_options(parameter_s,'n')
709 try:
700 try:
710 self.shell.del_var(varname, ('n' in opts))
701 self.shell.del_var(varname, ('n' in opts))
711 except (NameError, ValueError) as e:
702 except (NameError, ValueError) as e:
712 print(type(e).__name__ +": "+ str(e))
703 print(type(e).__name__ +": "+ str(e))
@@ -1,856 +1,854 b''
1 """Implementation of magic functions for interaction with the OS.
1 """Implementation of magic functions for interaction with the OS.
2
2
3 Note: this module is named 'osm' instead of 'os' to avoid a collision with the
3 Note: this module is named 'osm' instead of 'os' to avoid a collision with the
4 builtin.
4 builtin.
5 """
5 """
6 # Copyright (c) IPython Development Team.
6 # Copyright (c) IPython Development Team.
7 # Distributed under the terms of the Modified BSD License.
7 # Distributed under the terms of the Modified BSD License.
8
8
9 import io
9 import io
10 import os
10 import os
11 import re
11 import re
12 import sys
12 import sys
13 from pprint import pformat
13 from pprint import pformat
14
14
15 from IPython.core import magic_arguments
15 from IPython.core import magic_arguments
16 from IPython.core import oinspect
16 from IPython.core import oinspect
17 from IPython.core import page
17 from IPython.core import page
18 from IPython.core.alias import AliasError, Alias
18 from IPython.core.alias import AliasError, Alias
19 from IPython.core.error import UsageError
19 from IPython.core.error import UsageError
20 from IPython.core.magic import (
20 from IPython.core.magic import (
21 Magics, compress_dhist, magics_class, line_magic, cell_magic, line_cell_magic
21 Magics, compress_dhist, magics_class, line_magic, cell_magic, line_cell_magic
22 )
22 )
23 from IPython.testing.skipdoctest import skip_doctest
23 from IPython.testing.skipdoctest import skip_doctest
24 from IPython.utils.openpy import source_to_unicode
24 from IPython.utils.openpy import source_to_unicode
25 from IPython.utils.process import abbrev_cwd
25 from IPython.utils.process import abbrev_cwd
26 from IPython.utils.terminal import set_term_title
26 from IPython.utils.terminal import set_term_title
27 from traitlets import Bool
27 from traitlets import Bool
28 from warnings import warn
28 from warnings import warn
29
29
30
30
31 @magics_class
31 @magics_class
32 class OSMagics(Magics):
32 class OSMagics(Magics):
33 """Magics to interact with the underlying OS (shell-type functionality).
33 """Magics to interact with the underlying OS (shell-type functionality).
34 """
34 """
35
35
36 cd_force_quiet = Bool(False,
36 cd_force_quiet = Bool(False,
37 help="Force %cd magic to be quiet even if -q is not passed."
37 help="Force %cd magic to be quiet even if -q is not passed."
38 ).tag(config=True)
38 ).tag(config=True)
39
39
40 def __init__(self, shell=None, **kwargs):
40 def __init__(self, shell=None, **kwargs):
41
41
42 # Now define isexec in a cross platform manner.
42 # Now define isexec in a cross platform manner.
43 self.is_posix = False
43 self.is_posix = False
44 self.execre = None
44 self.execre = None
45 if os.name == 'posix':
45 if os.name == 'posix':
46 self.is_posix = True
46 self.is_posix = True
47 else:
47 else:
48 try:
48 try:
49 winext = os.environ['pathext'].replace(';','|').replace('.','')
49 winext = os.environ['pathext'].replace(';','|').replace('.','')
50 except KeyError:
50 except KeyError:
51 winext = 'exe|com|bat|py'
51 winext = 'exe|com|bat|py'
52 try:
52 try:
53 self.execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
53 self.execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
54 except re.error:
54 except re.error:
55 warn("Seems like your pathext environmental "
55 warn("Seems like your pathext environmental "
56 "variable is malformed. Please check it to "
56 "variable is malformed. Please check it to "
57 "enable a proper handle of file extensions "
57 "enable a proper handle of file extensions "
58 "managed for your system")
58 "managed for your system")
59 winext = 'exe|com|bat|py'
59 winext = 'exe|com|bat|py'
60 self.execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
60 self.execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
61
61
62 # call up the chain
62 # call up the chain
63 super().__init__(shell=shell, **kwargs)
63 super().__init__(shell=shell, **kwargs)
64
64
65
65
66 def _isexec_POSIX(self, file):
66 def _isexec_POSIX(self, file):
67 """
67 """
68 Test for executable on a POSIX system
68 Test for executable on a POSIX system
69 """
69 """
70 if os.access(file.path, os.X_OK):
70 if os.access(file.path, os.X_OK):
71 # will fail on maxOS if access is not X_OK
71 # will fail on maxOS if access is not X_OK
72 return file.is_file()
72 return file.is_file()
73 return False
73 return False
74
74
75
75
76
76
77 def _isexec_WIN(self, file):
77 def _isexec_WIN(self, file):
78 """
78 """
79 Test for executable file on non POSIX system
79 Test for executable file on non POSIX system
80 """
80 """
81 return file.is_file() and self.execre.match(file.name) is not None
81 return file.is_file() and self.execre.match(file.name) is not None
82
82
83 def isexec(self, file):
83 def isexec(self, file):
84 """
84 """
85 Test for executable file on non POSIX system
85 Test for executable file on non POSIX system
86 """
86 """
87 if self.is_posix:
87 if self.is_posix:
88 return self._isexec_POSIX(file)
88 return self._isexec_POSIX(file)
89 else:
89 else:
90 return self._isexec_WIN(file)
90 return self._isexec_WIN(file)
91
91
92
92
93 @skip_doctest
93 @skip_doctest
94 @line_magic
94 @line_magic
95 def alias(self, parameter_s=''):
95 def alias(self, parameter_s=''):
96 """Define an alias for a system command.
96 """Define an alias for a system command.
97
97
98 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
98 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
99
99
100 Then, typing 'alias_name params' will execute the system command 'cmd
100 Then, typing 'alias_name params' will execute the system command 'cmd
101 params' (from your underlying operating system).
101 params' (from your underlying operating system).
102
102
103 Aliases have lower precedence than magic functions and Python normal
103 Aliases have lower precedence than magic functions and Python normal
104 variables, so if 'foo' is both a Python variable and an alias, the
104 variables, so if 'foo' is both a Python variable and an alias, the
105 alias can not be executed until 'del foo' removes the Python variable.
105 alias can not be executed until 'del foo' removes the Python variable.
106
106
107 You can use the %l specifier in an alias definition to represent the
107 You can use the %l specifier in an alias definition to represent the
108 whole line when the alias is called. For example::
108 whole line when the alias is called. For example::
109
109
110 In [2]: alias bracket echo "Input in brackets: <%l>"
110 In [2]: alias bracket echo "Input in brackets: <%l>"
111 In [3]: bracket hello world
111 In [3]: bracket hello world
112 Input in brackets: <hello world>
112 Input in brackets: <hello world>
113
113
114 You can also define aliases with parameters using %s specifiers (one
114 You can also define aliases with parameters using %s specifiers (one
115 per parameter)::
115 per parameter)::
116
116
117 In [1]: alias parts echo first %s second %s
117 In [1]: alias parts echo first %s second %s
118 In [2]: %parts A B
118 In [2]: %parts A B
119 first A second B
119 first A second B
120 In [3]: %parts A
120 In [3]: %parts A
121 Incorrect number of arguments: 2 expected.
121 Incorrect number of arguments: 2 expected.
122 parts is an alias to: 'echo first %s second %s'
122 parts is an alias to: 'echo first %s second %s'
123
123
124 Note that %l and %s are mutually exclusive. You can only use one or
124 Note that %l and %s are mutually exclusive. You can only use one or
125 the other in your aliases.
125 the other in your aliases.
126
126
127 Aliases expand Python variables just like system calls using ! or !!
127 Aliases expand Python variables just like system calls using ! or !!
128 do: all expressions prefixed with '$' get expanded. For details of
128 do: all expressions prefixed with '$' get expanded. For details of
129 the semantic rules, see PEP-215:
129 the semantic rules, see PEP-215:
130 http://www.python.org/peps/pep-0215.html. This is the library used by
130 http://www.python.org/peps/pep-0215.html. This is the library used by
131 IPython for variable expansion. If you want to access a true shell
131 IPython for variable expansion. If you want to access a true shell
132 variable, an extra $ is necessary to prevent its expansion by
132 variable, an extra $ is necessary to prevent its expansion by
133 IPython::
133 IPython::
134
134
135 In [6]: alias show echo
135 In [6]: alias show echo
136 In [7]: PATH='A Python string'
136 In [7]: PATH='A Python string'
137 In [8]: show $PATH
137 In [8]: show $PATH
138 A Python string
138 A Python string
139 In [9]: show $$PATH
139 In [9]: show $$PATH
140 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
140 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
141
141
142 You can use the alias facility to access all of $PATH. See the %rehashx
142 You can use the alias facility to access all of $PATH. See the %rehashx
143 function, which automatically creates aliases for the contents of your
143 function, which automatically creates aliases for the contents of your
144 $PATH.
144 $PATH.
145
145
146 If called with no parameters, %alias prints the current alias table
146 If called with no parameters, %alias prints the current alias table
147 for your system. For posix systems, the default aliases are 'cat',
147 for your system. For posix systems, the default aliases are 'cat',
148 'cp', 'mv', 'rm', 'rmdir', and 'mkdir', and other platform-specific
148 'cp', 'mv', 'rm', 'rmdir', and 'mkdir', and other platform-specific
149 aliases are added. For windows-based systems, the default aliases are
149 aliases are added. For windows-based systems, the default aliases are
150 'copy', 'ddir', 'echo', 'ls', 'ldir', 'mkdir', 'ren', and 'rmdir'.
150 'copy', 'ddir', 'echo', 'ls', 'ldir', 'mkdir', 'ren', and 'rmdir'.
151
151
152 You can see the definition of alias by adding a question mark in the
152 You can see the definition of alias by adding a question mark in the
153 end::
153 end::
154
154
155 In [1]: cat?
155 In [1]: cat?
156 Repr: <alias cat for 'cat'>"""
156 Repr: <alias cat for 'cat'>"""
157
157
158 par = parameter_s.strip()
158 par = parameter_s.strip()
159 if not par:
159 if not par:
160 aliases = sorted(self.shell.alias_manager.aliases)
160 aliases = sorted(self.shell.alias_manager.aliases)
161 # stored = self.shell.db.get('stored_aliases', {} )
161 # stored = self.shell.db.get('stored_aliases', {} )
162 # for k, v in stored:
162 # for k, v in stored:
163 # atab.append(k, v[0])
163 # atab.append(k, v[0])
164
164
165 print("Total number of aliases:", len(aliases))
165 print("Total number of aliases:", len(aliases))
166 sys.stdout.flush()
166 sys.stdout.flush()
167 return aliases
167 return aliases
168
168
169 # Now try to define a new one
169 # Now try to define a new one
170 try:
170 try:
171 alias,cmd = par.split(None, 1)
171 alias,cmd = par.split(None, 1)
172 except TypeError:
172 except TypeError:
173 print(oinspect.getdoc(self.alias))
173 print(oinspect.getdoc(self.alias))
174 return
174 return
175
175
176 try:
176 try:
177 self.shell.alias_manager.define_alias(alias, cmd)
177 self.shell.alias_manager.define_alias(alias, cmd)
178 except AliasError as e:
178 except AliasError as e:
179 print(e)
179 print(e)
180 # end magic_alias
180 # end magic_alias
181
181
182 @line_magic
182 @line_magic
183 def unalias(self, parameter_s=''):
183 def unalias(self, parameter_s=''):
184 """Remove an alias"""
184 """Remove an alias"""
185
185
186 aname = parameter_s.strip()
186 aname = parameter_s.strip()
187 try:
187 try:
188 self.shell.alias_manager.undefine_alias(aname)
188 self.shell.alias_manager.undefine_alias(aname)
189 except ValueError as e:
189 except ValueError as e:
190 print(e)
190 print(e)
191 return
191 return
192
192
193 stored = self.shell.db.get('stored_aliases', {} )
193 stored = self.shell.db.get('stored_aliases', {} )
194 if aname in stored:
194 if aname in stored:
195 print("Removing %stored alias",aname)
195 print("Removing %stored alias",aname)
196 del stored[aname]
196 del stored[aname]
197 self.shell.db['stored_aliases'] = stored
197 self.shell.db['stored_aliases'] = stored
198
198
199 @line_magic
199 @line_magic
200 def rehashx(self, parameter_s=''):
200 def rehashx(self, parameter_s=''):
201 """Update the alias table with all executable files in $PATH.
201 """Update the alias table with all executable files in $PATH.
202
202
203 rehashx explicitly checks that every entry in $PATH is a file
203 rehashx explicitly checks that every entry in $PATH is a file
204 with execute access (os.X_OK).
204 with execute access (os.X_OK).
205
205
206 Under Windows, it checks executability as a match against a
206 Under Windows, it checks executability as a match against a
207 '|'-separated string of extensions, stored in the IPython config
207 '|'-separated string of extensions, stored in the IPython config
208 variable win_exec_ext. This defaults to 'exe|com|bat'.
208 variable win_exec_ext. This defaults to 'exe|com|bat'.
209
209
210 This function also resets the root module cache of module completer,
210 This function also resets the root module cache of module completer,
211 used on slow filesystems.
211 used on slow filesystems.
212 """
212 """
213 from IPython.core.alias import InvalidAliasError
213 from IPython.core.alias import InvalidAliasError
214
214
215 # for the benefit of module completer in ipy_completers.py
215 # for the benefit of module completer in ipy_completers.py
216 del self.shell.db['rootmodules_cache']
216 del self.shell.db['rootmodules_cache']
217
217
218 path = [os.path.abspath(os.path.expanduser(p)) for p in
218 path = [os.path.abspath(os.path.expanduser(p)) for p in
219 os.environ.get('PATH','').split(os.pathsep)]
219 os.environ.get('PATH','').split(os.pathsep)]
220
220
221 syscmdlist = []
221 syscmdlist = []
222 savedir = os.getcwd()
222 savedir = os.getcwd()
223
223
224 # Now walk the paths looking for executables to alias.
224 # Now walk the paths looking for executables to alias.
225 try:
225 try:
226 # write the whole loop for posix/Windows so we don't have an if in
226 # write the whole loop for posix/Windows so we don't have an if in
227 # the innermost part
227 # the innermost part
228 if self.is_posix:
228 if self.is_posix:
229 for pdir in path:
229 for pdir in path:
230 try:
230 try:
231 os.chdir(pdir)
231 os.chdir(pdir)
232 except OSError:
232 except OSError:
233 continue
233 continue
234
234
235 # for python 3.6+ rewrite to: with os.scandir(pdir) as dirlist:
235 # for python 3.6+ rewrite to: with os.scandir(pdir) as dirlist:
236 dirlist = os.scandir(path=pdir)
236 dirlist = os.scandir(path=pdir)
237 for ff in dirlist:
237 for ff in dirlist:
238 if self.isexec(ff):
238 if self.isexec(ff):
239 fname = ff.name
239 fname = ff.name
240 try:
240 try:
241 # Removes dots from the name since ipython
241 # Removes dots from the name since ipython
242 # will assume names with dots to be python.
242 # will assume names with dots to be python.
243 if not self.shell.alias_manager.is_alias(fname):
243 if not self.shell.alias_manager.is_alias(fname):
244 self.shell.alias_manager.define_alias(
244 self.shell.alias_manager.define_alias(
245 fname.replace('.',''), fname)
245 fname.replace('.',''), fname)
246 except InvalidAliasError:
246 except InvalidAliasError:
247 pass
247 pass
248 else:
248 else:
249 syscmdlist.append(fname)
249 syscmdlist.append(fname)
250 else:
250 else:
251 no_alias = Alias.blacklist
251 no_alias = Alias.blacklist
252 for pdir in path:
252 for pdir in path:
253 try:
253 try:
254 os.chdir(pdir)
254 os.chdir(pdir)
255 except OSError:
255 except OSError:
256 continue
256 continue
257
257
258 # for python 3.6+ rewrite to: with os.scandir(pdir) as dirlist:
258 # for python 3.6+ rewrite to: with os.scandir(pdir) as dirlist:
259 dirlist = os.scandir(pdir)
259 dirlist = os.scandir(pdir)
260 for ff in dirlist:
260 for ff in dirlist:
261 fname = ff.name
261 fname = ff.name
262 base, ext = os.path.splitext(fname)
262 base, ext = os.path.splitext(fname)
263 if self.isexec(ff) and base.lower() not in no_alias:
263 if self.isexec(ff) and base.lower() not in no_alias:
264 if ext.lower() == '.exe':
264 if ext.lower() == '.exe':
265 fname = base
265 fname = base
266 try:
266 try:
267 # Removes dots from the name since ipython
267 # Removes dots from the name since ipython
268 # will assume names with dots to be python.
268 # will assume names with dots to be python.
269 self.shell.alias_manager.define_alias(
269 self.shell.alias_manager.define_alias(
270 base.lower().replace('.',''), fname)
270 base.lower().replace('.',''), fname)
271 except InvalidAliasError:
271 except InvalidAliasError:
272 pass
272 pass
273 syscmdlist.append(fname)
273 syscmdlist.append(fname)
274
274
275 self.shell.db['syscmdlist'] = syscmdlist
275 self.shell.db['syscmdlist'] = syscmdlist
276 finally:
276 finally:
277 os.chdir(savedir)
277 os.chdir(savedir)
278
278
279 @skip_doctest
279 @skip_doctest
280 @line_magic
280 @line_magic
281 def pwd(self, parameter_s=''):
281 def pwd(self, parameter_s=''):
282 """Return the current working directory path.
282 """Return the current working directory path.
283
283
284 Examples
284 Examples
285 --------
285 --------
286 ::
286 ::
287
287
288 In [9]: pwd
288 In [9]: pwd
289 Out[9]: '/home/tsuser/sprint/ipython'
289 Out[9]: '/home/tsuser/sprint/ipython'
290 """
290 """
291 try:
291 try:
292 return os.getcwd()
292 return os.getcwd()
293 except FileNotFoundError as e:
293 except FileNotFoundError as e:
294 raise UsageError("CWD no longer exists - please use %cd to change directory.") from e
294 raise UsageError("CWD no longer exists - please use %cd to change directory.") from e
295
295
296 @skip_doctest
296 @skip_doctest
297 @line_magic
297 @line_magic
298 def cd(self, parameter_s=''):
298 def cd(self, parameter_s=''):
299 """Change the current working directory.
299 """Change the current working directory.
300
300
301 This command automatically maintains an internal list of directories
301 This command automatically maintains an internal list of directories
302 you visit during your IPython session, in the variable ``_dh``. The
302 you visit during your IPython session, in the variable ``_dh``. The
303 command :magic:`%dhist` shows this history nicely formatted. You can
303 command :magic:`%dhist` shows this history nicely formatted. You can
304 also do ``cd -<tab>`` to see directory history conveniently.
304 also do ``cd -<tab>`` to see directory history conveniently.
305 Usage:
305 Usage:
306
306
307 - ``cd 'dir'``: changes to directory 'dir'.
307 - ``cd 'dir'``: changes to directory 'dir'.
308 - ``cd -``: changes to the last visited directory.
308 - ``cd -``: changes to the last visited directory.
309 - ``cd -<n>``: changes to the n-th directory in the directory history.
309 - ``cd -<n>``: changes to the n-th directory in the directory history.
310 - ``cd --foo``: change to directory that matches 'foo' in history
310 - ``cd --foo``: change to directory that matches 'foo' in history
311 - ``cd -b <bookmark_name>``: jump to a bookmark set by %bookmark
311 - ``cd -b <bookmark_name>``: jump to a bookmark set by %bookmark
312 - Hitting a tab key after ``cd -b`` allows you to tab-complete
312 - Hitting a tab key after ``cd -b`` allows you to tab-complete
313 bookmark names.
313 bookmark names.
314
314
315 .. note::
315 .. note::
316 ``cd <bookmark_name>`` is enough if there is no directory
316 ``cd <bookmark_name>`` is enough if there is no directory
317 ``<bookmark_name>``, but a bookmark with the name exists.
317 ``<bookmark_name>``, but a bookmark with the name exists.
318
318
319
320 Options:
319 Options:
321
320
322 -q Be quiet. Do not print the working directory after the
321 -q Be quiet. Do not print the working directory after the
323 cd command is executed. By default IPython's cd
322 cd command is executed. By default IPython's cd
324 command does print this directory, since the default
323 command does print this directory, since the default
325 prompts do not display path information.
324 prompts do not display path information.
326
325
327 .. note::
326 .. note::
328 Note that ``!cd`` doesn't work for this purpose because the shell
327 Note that ``!cd`` doesn't work for this purpose because the shell
329 where ``!command`` runs is immediately discarded after executing
328 where ``!command`` runs is immediately discarded after executing
330 'command'.
329 'command'.
331
330
332
333 Examples
331 Examples
334 --------
332 --------
335 ::
333 ::
336
334
337 In [10]: cd parent/child
335 In [10]: cd parent/child
338 /home/tsuser/parent/child
336 /home/tsuser/parent/child
339 """
337 """
340
338
341 try:
339 try:
342 oldcwd = os.getcwd()
340 oldcwd = os.getcwd()
343 except FileNotFoundError:
341 except FileNotFoundError:
344 # Happens if the CWD has been deleted.
342 # Happens if the CWD has been deleted.
345 oldcwd = None
343 oldcwd = None
346
344
347 numcd = re.match(r'(-)(\d+)$',parameter_s)
345 numcd = re.match(r'(-)(\d+)$',parameter_s)
348 # jump in directory history by number
346 # jump in directory history by number
349 if numcd:
347 if numcd:
350 nn = int(numcd.group(2))
348 nn = int(numcd.group(2))
351 try:
349 try:
352 ps = self.shell.user_ns['_dh'][nn]
350 ps = self.shell.user_ns['_dh'][nn]
353 except IndexError:
351 except IndexError:
354 print('The requested directory does not exist in history.')
352 print('The requested directory does not exist in history.')
355 return
353 return
356 else:
354 else:
357 opts = {}
355 opts = {}
358 elif parameter_s.startswith('--'):
356 elif parameter_s.startswith('--'):
359 ps = None
357 ps = None
360 fallback = None
358 fallback = None
361 pat = parameter_s[2:]
359 pat = parameter_s[2:]
362 dh = self.shell.user_ns['_dh']
360 dh = self.shell.user_ns['_dh']
363 # first search only by basename (last component)
361 # first search only by basename (last component)
364 for ent in reversed(dh):
362 for ent in reversed(dh):
365 if pat in os.path.basename(ent) and os.path.isdir(ent):
363 if pat in os.path.basename(ent) and os.path.isdir(ent):
366 ps = ent
364 ps = ent
367 break
365 break
368
366
369 if fallback is None and pat in ent and os.path.isdir(ent):
367 if fallback is None and pat in ent and os.path.isdir(ent):
370 fallback = ent
368 fallback = ent
371
369
372 # if we have no last part match, pick the first full path match
370 # if we have no last part match, pick the first full path match
373 if ps is None:
371 if ps is None:
374 ps = fallback
372 ps = fallback
375
373
376 if ps is None:
374 if ps is None:
377 print("No matching entry in directory history")
375 print("No matching entry in directory history")
378 return
376 return
379 else:
377 else:
380 opts = {}
378 opts = {}
381
379
382
380
383 else:
381 else:
384 opts, ps = self.parse_options(parameter_s, 'qb', mode='string')
382 opts, ps = self.parse_options(parameter_s, 'qb', mode='string')
385 # jump to previous
383 # jump to previous
386 if ps == '-':
384 if ps == '-':
387 try:
385 try:
388 ps = self.shell.user_ns['_dh'][-2]
386 ps = self.shell.user_ns['_dh'][-2]
389 except IndexError as e:
387 except IndexError as e:
390 raise UsageError('%cd -: No previous directory to change to.') from e
388 raise UsageError('%cd -: No previous directory to change to.') from e
391 # jump to bookmark if needed
389 # jump to bookmark if needed
392 else:
390 else:
393 if not os.path.isdir(ps) or 'b' in opts:
391 if not os.path.isdir(ps) or 'b' in opts:
394 bkms = self.shell.db.get('bookmarks', {})
392 bkms = self.shell.db.get('bookmarks', {})
395
393
396 if ps in bkms:
394 if ps in bkms:
397 target = bkms[ps]
395 target = bkms[ps]
398 print('(bookmark:%s) -> %s' % (ps, target))
396 print('(bookmark:%s) -> %s' % (ps, target))
399 ps = target
397 ps = target
400 else:
398 else:
401 if 'b' in opts:
399 if 'b' in opts:
402 raise UsageError("Bookmark '%s' not found. "
400 raise UsageError("Bookmark '%s' not found. "
403 "Use '%%bookmark -l' to see your bookmarks." % ps)
401 "Use '%%bookmark -l' to see your bookmarks." % ps)
404
402
405 # at this point ps should point to the target dir
403 # at this point ps should point to the target dir
406 if ps:
404 if ps:
407 try:
405 try:
408 os.chdir(os.path.expanduser(ps))
406 os.chdir(os.path.expanduser(ps))
409 if hasattr(self.shell, 'term_title') and self.shell.term_title:
407 if hasattr(self.shell, 'term_title') and self.shell.term_title:
410 set_term_title(self.shell.term_title_format.format(cwd=abbrev_cwd()))
408 set_term_title(self.shell.term_title_format.format(cwd=abbrev_cwd()))
411 except OSError:
409 except OSError:
412 print(sys.exc_info()[1])
410 print(sys.exc_info()[1])
413 else:
411 else:
414 cwd = os.getcwd()
412 cwd = os.getcwd()
415 dhist = self.shell.user_ns['_dh']
413 dhist = self.shell.user_ns['_dh']
416 if oldcwd != cwd:
414 if oldcwd != cwd:
417 dhist.append(cwd)
415 dhist.append(cwd)
418 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
416 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
419
417
420 else:
418 else:
421 os.chdir(self.shell.home_dir)
419 os.chdir(self.shell.home_dir)
422 if hasattr(self.shell, 'term_title') and self.shell.term_title:
420 if hasattr(self.shell, 'term_title') and self.shell.term_title:
423 set_term_title(self.shell.term_title_format.format(cwd="~"))
421 set_term_title(self.shell.term_title_format.format(cwd="~"))
424 cwd = os.getcwd()
422 cwd = os.getcwd()
425 dhist = self.shell.user_ns['_dh']
423 dhist = self.shell.user_ns['_dh']
426
424
427 if oldcwd != cwd:
425 if oldcwd != cwd:
428 dhist.append(cwd)
426 dhist.append(cwd)
429 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
427 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
430 if not 'q' in opts and not self.cd_force_quiet and self.shell.user_ns['_dh']:
428 if not 'q' in opts and not self.cd_force_quiet and self.shell.user_ns['_dh']:
431 print(self.shell.user_ns['_dh'][-1])
429 print(self.shell.user_ns['_dh'][-1])
432
430
433 @line_magic
431 @line_magic
434 def env(self, parameter_s=''):
432 def env(self, parameter_s=''):
435 """Get, set, or list environment variables.
433 """Get, set, or list environment variables.
436
434
437 Usage:\\
435 Usage:\\
438
436
439 :``%env``: lists all environment variables/values
437 :``%env``: lists all environment variables/values
440 :``%env var``: get value for var
438 :``%env var``: get value for var
441 :``%env var val``: set value for var
439 :``%env var val``: set value for var
442 :``%env var=val``: set value for var
440 :``%env var=val``: set value for var
443 :``%env var=$val``: set value for var, using python expansion if possible
441 :``%env var=$val``: set value for var, using python expansion if possible
444 """
442 """
445 if parameter_s.strip():
443 if parameter_s.strip():
446 split = '=' if '=' in parameter_s else ' '
444 split = '=' if '=' in parameter_s else ' '
447 bits = parameter_s.split(split)
445 bits = parameter_s.split(split)
448 if len(bits) == 1:
446 if len(bits) == 1:
449 key = parameter_s.strip()
447 key = parameter_s.strip()
450 if key in os.environ:
448 if key in os.environ:
451 return os.environ[key]
449 return os.environ[key]
452 else:
450 else:
453 err = "Environment does not have key: {0}".format(key)
451 err = "Environment does not have key: {0}".format(key)
454 raise UsageError(err)
452 raise UsageError(err)
455 if len(bits) > 1:
453 if len(bits) > 1:
456 return self.set_env(parameter_s)
454 return self.set_env(parameter_s)
457 env = dict(os.environ)
455 env = dict(os.environ)
458 # hide likely secrets when printing the whole environment
456 # hide likely secrets when printing the whole environment
459 for key in list(env):
457 for key in list(env):
460 if any(s in key.lower() for s in ('key', 'token', 'secret')):
458 if any(s in key.lower() for s in ('key', 'token', 'secret')):
461 env[key] = '<hidden>'
459 env[key] = '<hidden>'
462
460
463 return env
461 return env
464
462
465 @line_magic
463 @line_magic
466 def set_env(self, parameter_s):
464 def set_env(self, parameter_s):
467 """Set environment variables. Assumptions are that either "val" is a
465 """Set environment variables. Assumptions are that either "val" is a
468 name in the user namespace, or val is something that evaluates to a
466 name in the user namespace, or val is something that evaluates to a
469 string.
467 string.
470
468
471 Usage:\\
469 Usage:\\
472 %set_env var val: set value for var
470 %set_env var val: set value for var
473 %set_env var=val: set value for var
471 %set_env var=val: set value for var
474 %set_env var=$val: set value for var, using python expansion if possible
472 %set_env var=$val: set value for var, using python expansion if possible
475 """
473 """
476 split = '=' if '=' in parameter_s else ' '
474 split = '=' if '=' in parameter_s else ' '
477 bits = parameter_s.split(split, 1)
475 bits = parameter_s.split(split, 1)
478 if not parameter_s.strip() or len(bits)<2:
476 if not parameter_s.strip() or len(bits)<2:
479 raise UsageError("usage is 'set_env var=val'")
477 raise UsageError("usage is 'set_env var=val'")
480 var = bits[0].strip()
478 var = bits[0].strip()
481 val = bits[1].strip()
479 val = bits[1].strip()
482 if re.match(r'.*\s.*', var):
480 if re.match(r'.*\s.*', var):
483 # an environment variable with whitespace is almost certainly
481 # an environment variable with whitespace is almost certainly
484 # not what the user intended. what's more likely is the wrong
482 # not what the user intended. what's more likely is the wrong
485 # split was chosen, ie for "set_env cmd_args A=B", we chose
483 # split was chosen, ie for "set_env cmd_args A=B", we chose
486 # '=' for the split and should have chosen ' '. to get around
484 # '=' for the split and should have chosen ' '. to get around
487 # this, users should just assign directly to os.environ or use
485 # this, users should just assign directly to os.environ or use
488 # standard magic {var} expansion.
486 # standard magic {var} expansion.
489 err = "refusing to set env var with whitespace: '{0}'"
487 err = "refusing to set env var with whitespace: '{0}'"
490 err = err.format(val)
488 err = err.format(val)
491 raise UsageError(err)
489 raise UsageError(err)
492 os.environ[var] = val
490 os.environ[var] = val
493 print('env: {0}={1}'.format(var,val))
491 print('env: {0}={1}'.format(var,val))
494
492
495 @line_magic
493 @line_magic
496 def pushd(self, parameter_s=''):
494 def pushd(self, parameter_s=''):
497 """Place the current dir on stack and change directory.
495 """Place the current dir on stack and change directory.
498
496
499 Usage:\\
497 Usage:\\
500 %pushd ['dirname']
498 %pushd ['dirname']
501 """
499 """
502
500
503 dir_s = self.shell.dir_stack
501 dir_s = self.shell.dir_stack
504 tgt = os.path.expanduser(parameter_s)
502 tgt = os.path.expanduser(parameter_s)
505 cwd = os.getcwd().replace(self.shell.home_dir,'~')
503 cwd = os.getcwd().replace(self.shell.home_dir,'~')
506 if tgt:
504 if tgt:
507 self.cd(parameter_s)
505 self.cd(parameter_s)
508 dir_s.insert(0,cwd)
506 dir_s.insert(0,cwd)
509 return self.shell.run_line_magic('dirs', '')
507 return self.shell.run_line_magic('dirs', '')
510
508
511 @line_magic
509 @line_magic
512 def popd(self, parameter_s=''):
510 def popd(self, parameter_s=''):
513 """Change to directory popped off the top of the stack.
511 """Change to directory popped off the top of the stack.
514 """
512 """
515 if not self.shell.dir_stack:
513 if not self.shell.dir_stack:
516 raise UsageError("%popd on empty stack")
514 raise UsageError("%popd on empty stack")
517 top = self.shell.dir_stack.pop(0)
515 top = self.shell.dir_stack.pop(0)
518 self.cd(top)
516 self.cd(top)
519 print("popd ->",top)
517 print("popd ->",top)
520
518
521 @line_magic
519 @line_magic
522 def dirs(self, parameter_s=''):
520 def dirs(self, parameter_s=''):
523 """Return the current directory stack."""
521 """Return the current directory stack."""
524
522
525 return self.shell.dir_stack
523 return self.shell.dir_stack
526
524
527 @line_magic
525 @line_magic
528 def dhist(self, parameter_s=''):
526 def dhist(self, parameter_s=''):
529 """Print your history of visited directories.
527 """Print your history of visited directories.
530
528
531 %dhist -> print full history\\
529 %dhist -> print full history\\
532 %dhist n -> print last n entries only\\
530 %dhist n -> print last n entries only\\
533 %dhist n1 n2 -> print entries between n1 and n2 (n2 not included)\\
531 %dhist n1 n2 -> print entries between n1 and n2 (n2 not included)\\
534
532
535 This history is automatically maintained by the %cd command, and
533 This history is automatically maintained by the %cd command, and
536 always available as the global list variable _dh. You can use %cd -<n>
534 always available as the global list variable _dh. You can use %cd -<n>
537 to go to directory number <n>.
535 to go to directory number <n>.
538
536
539 Note that most of time, you should view directory history by entering
537 Note that most of time, you should view directory history by entering
540 cd -<TAB>.
538 cd -<TAB>.
541
539
542 """
540 """
543
541
544 dh = self.shell.user_ns['_dh']
542 dh = self.shell.user_ns['_dh']
545 if parameter_s:
543 if parameter_s:
546 try:
544 try:
547 args = map(int,parameter_s.split())
545 args = map(int,parameter_s.split())
548 except:
546 except:
549 self.arg_err(self.dhist)
547 self.arg_err(self.dhist)
550 return
548 return
551 if len(args) == 1:
549 if len(args) == 1:
552 ini,fin = max(len(dh)-(args[0]),0),len(dh)
550 ini,fin = max(len(dh)-(args[0]),0),len(dh)
553 elif len(args) == 2:
551 elif len(args) == 2:
554 ini,fin = args
552 ini,fin = args
555 fin = min(fin, len(dh))
553 fin = min(fin, len(dh))
556 else:
554 else:
557 self.arg_err(self.dhist)
555 self.arg_err(self.dhist)
558 return
556 return
559 else:
557 else:
560 ini,fin = 0,len(dh)
558 ini,fin = 0,len(dh)
561 print('Directory history (kept in _dh)')
559 print('Directory history (kept in _dh)')
562 for i in range(ini, fin):
560 for i in range(ini, fin):
563 print("%d: %s" % (i, dh[i]))
561 print("%d: %s" % (i, dh[i]))
564
562
565 @skip_doctest
563 @skip_doctest
566 @line_magic
564 @line_magic
567 def sc(self, parameter_s=''):
565 def sc(self, parameter_s=''):
568 """Shell capture - run shell command and capture output (DEPRECATED use !).
566 """Shell capture - run shell command and capture output (DEPRECATED use !).
569
567
570 DEPRECATED. Suboptimal, retained for backwards compatibility.
568 DEPRECATED. Suboptimal, retained for backwards compatibility.
571
569
572 You should use the form 'var = !command' instead. Example:
570 You should use the form 'var = !command' instead. Example:
573
571
574 "%sc -l myfiles = ls ~" should now be written as
572 "%sc -l myfiles = ls ~" should now be written as
575
573
576 "myfiles = !ls ~"
574 "myfiles = !ls ~"
577
575
578 myfiles.s, myfiles.l and myfiles.n still apply as documented
576 myfiles.s, myfiles.l and myfiles.n still apply as documented
579 below.
577 below.
580
578
581 --
579 --
582 %sc [options] varname=command
580 %sc [options] varname=command
583
581
584 IPython will run the given command using commands.getoutput(), and
582 IPython will run the given command using commands.getoutput(), and
585 will then update the user's interactive namespace with a variable
583 will then update the user's interactive namespace with a variable
586 called varname, containing the value of the call. Your command can
584 called varname, containing the value of the call. Your command can
587 contain shell wildcards, pipes, etc.
585 contain shell wildcards, pipes, etc.
588
586
589 The '=' sign in the syntax is mandatory, and the variable name you
587 The '=' sign in the syntax is mandatory, and the variable name you
590 supply must follow Python's standard conventions for valid names.
588 supply must follow Python's standard conventions for valid names.
591
589
592 (A special format without variable name exists for internal use)
590 (A special format without variable name exists for internal use)
593
591
594 Options:
592 Options:
595
593
596 -l: list output. Split the output on newlines into a list before
594 -l: list output. Split the output on newlines into a list before
597 assigning it to the given variable. By default the output is stored
595 assigning it to the given variable. By default the output is stored
598 as a single string.
596 as a single string.
599
597
600 -v: verbose. Print the contents of the variable.
598 -v: verbose. Print the contents of the variable.
601
599
602 In most cases you should not need to split as a list, because the
600 In most cases you should not need to split as a list, because the
603 returned value is a special type of string which can automatically
601 returned value is a special type of string which can automatically
604 provide its contents either as a list (split on newlines) or as a
602 provide its contents either as a list (split on newlines) or as a
605 space-separated string. These are convenient, respectively, either
603 space-separated string. These are convenient, respectively, either
606 for sequential processing or to be passed to a shell command.
604 for sequential processing or to be passed to a shell command.
607
605
608 For example::
606 For example::
609
607
610 # Capture into variable a
608 # Capture into variable a
611 In [1]: sc a=ls *py
609 In [1]: sc a=ls *py
612
610
613 # a is a string with embedded newlines
611 # a is a string with embedded newlines
614 In [2]: a
612 In [2]: a
615 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
613 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
616
614
617 # which can be seen as a list:
615 # which can be seen as a list:
618 In [3]: a.l
616 In [3]: a.l
619 Out[3]: ['setup.py', 'win32_manual_post_install.py']
617 Out[3]: ['setup.py', 'win32_manual_post_install.py']
620
618
621 # or as a whitespace-separated string:
619 # or as a whitespace-separated string:
622 In [4]: a.s
620 In [4]: a.s
623 Out[4]: 'setup.py win32_manual_post_install.py'
621 Out[4]: 'setup.py win32_manual_post_install.py'
624
622
625 # a.s is useful to pass as a single command line:
623 # a.s is useful to pass as a single command line:
626 In [5]: !wc -l $a.s
624 In [5]: !wc -l $a.s
627 146 setup.py
625 146 setup.py
628 130 win32_manual_post_install.py
626 130 win32_manual_post_install.py
629 276 total
627 276 total
630
628
631 # while the list form is useful to loop over:
629 # while the list form is useful to loop over:
632 In [6]: for f in a.l:
630 In [6]: for f in a.l:
633 ...: !wc -l $f
631 ...: !wc -l $f
634 ...:
632 ...:
635 146 setup.py
633 146 setup.py
636 130 win32_manual_post_install.py
634 130 win32_manual_post_install.py
637
635
638 Similarly, the lists returned by the -l option are also special, in
636 Similarly, the lists returned by the -l option are also special, in
639 the sense that you can equally invoke the .s attribute on them to
637 the sense that you can equally invoke the .s attribute on them to
640 automatically get a whitespace-separated string from their contents::
638 automatically get a whitespace-separated string from their contents::
641
639
642 In [7]: sc -l b=ls *py
640 In [7]: sc -l b=ls *py
643
641
644 In [8]: b
642 In [8]: b
645 Out[8]: ['setup.py', 'win32_manual_post_install.py']
643 Out[8]: ['setup.py', 'win32_manual_post_install.py']
646
644
647 In [9]: b.s
645 In [9]: b.s
648 Out[9]: 'setup.py win32_manual_post_install.py'
646 Out[9]: 'setup.py win32_manual_post_install.py'
649
647
650 In summary, both the lists and strings used for output capture have
648 In summary, both the lists and strings used for output capture have
651 the following special attributes::
649 the following special attributes::
652
650
653 .l (or .list) : value as list.
651 .l (or .list) : value as list.
654 .n (or .nlstr): value as newline-separated string.
652 .n (or .nlstr): value as newline-separated string.
655 .s (or .spstr): value as space-separated string.
653 .s (or .spstr): value as space-separated string.
656 """
654 """
657
655
658 opts,args = self.parse_options(parameter_s, 'lv')
656 opts,args = self.parse_options(parameter_s, 'lv')
659 # Try to get a variable name and command to run
657 # Try to get a variable name and command to run
660 try:
658 try:
661 # the variable name must be obtained from the parse_options
659 # the variable name must be obtained from the parse_options
662 # output, which uses shlex.split to strip options out.
660 # output, which uses shlex.split to strip options out.
663 var,_ = args.split('=', 1)
661 var,_ = args.split('=', 1)
664 var = var.strip()
662 var = var.strip()
665 # But the command has to be extracted from the original input
663 # But the command has to be extracted from the original input
666 # parameter_s, not on what parse_options returns, to avoid the
664 # parameter_s, not on what parse_options returns, to avoid the
667 # quote stripping which shlex.split performs on it.
665 # quote stripping which shlex.split performs on it.
668 _,cmd = parameter_s.split('=', 1)
666 _,cmd = parameter_s.split('=', 1)
669 except ValueError:
667 except ValueError:
670 var,cmd = '',''
668 var,cmd = '',''
671 # If all looks ok, proceed
669 # If all looks ok, proceed
672 split = 'l' in opts
670 split = 'l' in opts
673 out = self.shell.getoutput(cmd, split=split)
671 out = self.shell.getoutput(cmd, split=split)
674 if 'v' in opts:
672 if 'v' in opts:
675 print('%s ==\n%s' % (var, pformat(out)))
673 print('%s ==\n%s' % (var, pformat(out)))
676 if var:
674 if var:
677 self.shell.user_ns.update({var:out})
675 self.shell.user_ns.update({var:out})
678 else:
676 else:
679 return out
677 return out
680
678
681 @line_cell_magic
679 @line_cell_magic
682 def sx(self, line='', cell=None):
680 def sx(self, line='', cell=None):
683 """Shell execute - run shell command and capture output (!! is short-hand).
681 """Shell execute - run shell command and capture output (!! is short-hand).
684
682
685 %sx command
683 %sx command
686
684
687 IPython will run the given command using commands.getoutput(), and
685 IPython will run the given command using commands.getoutput(), and
688 return the result formatted as a list (split on '\\n'). Since the
686 return the result formatted as a list (split on '\\n'). Since the
689 output is _returned_, it will be stored in ipython's regular output
687 output is _returned_, it will be stored in ipython's regular output
690 cache Out[N] and in the '_N' automatic variables.
688 cache Out[N] and in the '_N' automatic variables.
691
689
692 Notes:
690 Notes:
693
691
694 1) If an input line begins with '!!', then %sx is automatically
692 1) If an input line begins with '!!', then %sx is automatically
695 invoked. That is, while::
693 invoked. That is, while::
696
694
697 !ls
695 !ls
698
696
699 causes ipython to simply issue system('ls'), typing::
697 causes ipython to simply issue system('ls'), typing::
700
698
701 !!ls
699 !!ls
702
700
703 is a shorthand equivalent to::
701 is a shorthand equivalent to::
704
702
705 %sx ls
703 %sx ls
706
704
707 2) %sx differs from %sc in that %sx automatically splits into a list,
705 2) %sx differs from %sc in that %sx automatically splits into a list,
708 like '%sc -l'. The reason for this is to make it as easy as possible
706 like '%sc -l'. The reason for this is to make it as easy as possible
709 to process line-oriented shell output via further python commands.
707 to process line-oriented shell output via further python commands.
710 %sc is meant to provide much finer control, but requires more
708 %sc is meant to provide much finer control, but requires more
711 typing.
709 typing.
712
710
713 3) Just like %sc -l, this is a list with special attributes:
711 3) Just like %sc -l, this is a list with special attributes:
714 ::
712 ::
715
713
716 .l (or .list) : value as list.
714 .l (or .list) : value as list.
717 .n (or .nlstr): value as newline-separated string.
715 .n (or .nlstr): value as newline-separated string.
718 .s (or .spstr): value as whitespace-separated string.
716 .s (or .spstr): value as whitespace-separated string.
719
717
720 This is very useful when trying to use such lists as arguments to
718 This is very useful when trying to use such lists as arguments to
721 system commands."""
719 system commands."""
722
720
723 if cell is None:
721 if cell is None:
724 # line magic
722 # line magic
725 return self.shell.getoutput(line)
723 return self.shell.getoutput(line)
726 else:
724 else:
727 opts,args = self.parse_options(line, '', 'out=')
725 opts,args = self.parse_options(line, '', 'out=')
728 output = self.shell.getoutput(cell)
726 output = self.shell.getoutput(cell)
729 out_name = opts.get('out', opts.get('o'))
727 out_name = opts.get('out', opts.get('o'))
730 if out_name:
728 if out_name:
731 self.shell.user_ns[out_name] = output
729 self.shell.user_ns[out_name] = output
732 else:
730 else:
733 return output
731 return output
734
732
735 system = line_cell_magic('system')(sx)
733 system = line_cell_magic('system')(sx)
736 bang = cell_magic('!')(sx)
734 bang = cell_magic('!')(sx)
737
735
738 @line_magic
736 @line_magic
739 def bookmark(self, parameter_s=''):
737 def bookmark(self, parameter_s=''):
740 """Manage IPython's bookmark system.
738 """Manage IPython's bookmark system.
741
739
742 %bookmark <name> - set bookmark to current dir
740 %bookmark <name> - set bookmark to current dir
743 %bookmark <name> <dir> - set bookmark to <dir>
741 %bookmark <name> <dir> - set bookmark to <dir>
744 %bookmark -l - list all bookmarks
742 %bookmark -l - list all bookmarks
745 %bookmark -d <name> - remove bookmark
743 %bookmark -d <name> - remove bookmark
746 %bookmark -r - remove all bookmarks
744 %bookmark -r - remove all bookmarks
747
745
748 You can later on access a bookmarked folder with::
746 You can later on access a bookmarked folder with::
749
747
750 %cd -b <name>
748 %cd -b <name>
751
749
752 or simply '%cd <name>' if there is no directory called <name> AND
750 or simply '%cd <name>' if there is no directory called <name> AND
753 there is such a bookmark defined.
751 there is such a bookmark defined.
754
752
755 Your bookmarks persist through IPython sessions, but they are
753 Your bookmarks persist through IPython sessions, but they are
756 associated with each profile."""
754 associated with each profile."""
757
755
758 opts,args = self.parse_options(parameter_s,'drl',mode='list')
756 opts,args = self.parse_options(parameter_s,'drl',mode='list')
759 if len(args) > 2:
757 if len(args) > 2:
760 raise UsageError("%bookmark: too many arguments")
758 raise UsageError("%bookmark: too many arguments")
761
759
762 bkms = self.shell.db.get('bookmarks',{})
760 bkms = self.shell.db.get('bookmarks',{})
763
761
764 if 'd' in opts:
762 if 'd' in opts:
765 try:
763 try:
766 todel = args[0]
764 todel = args[0]
767 except IndexError as e:
765 except IndexError as e:
768 raise UsageError(
766 raise UsageError(
769 "%bookmark -d: must provide a bookmark to delete") from e
767 "%bookmark -d: must provide a bookmark to delete") from e
770 else:
768 else:
771 try:
769 try:
772 del bkms[todel]
770 del bkms[todel]
773 except KeyError as e:
771 except KeyError as e:
774 raise UsageError(
772 raise UsageError(
775 "%%bookmark -d: Can't delete bookmark '%s'" % todel) from e
773 "%%bookmark -d: Can't delete bookmark '%s'" % todel) from e
776
774
777 elif 'r' in opts:
775 elif 'r' in opts:
778 bkms = {}
776 bkms = {}
779 elif 'l' in opts:
777 elif 'l' in opts:
780 bks = sorted(bkms)
778 bks = sorted(bkms)
781 if bks:
779 if bks:
782 size = max(map(len, bks))
780 size = max(map(len, bks))
783 else:
781 else:
784 size = 0
782 size = 0
785 fmt = '%-'+str(size)+'s -> %s'
783 fmt = '%-'+str(size)+'s -> %s'
786 print('Current bookmarks:')
784 print('Current bookmarks:')
787 for bk in bks:
785 for bk in bks:
788 print(fmt % (bk, bkms[bk]))
786 print(fmt % (bk, bkms[bk]))
789 else:
787 else:
790 if not args:
788 if not args:
791 raise UsageError("%bookmark: You must specify the bookmark name")
789 raise UsageError("%bookmark: You must specify the bookmark name")
792 elif len(args)==1:
790 elif len(args)==1:
793 bkms[args[0]] = os.getcwd()
791 bkms[args[0]] = os.getcwd()
794 elif len(args)==2:
792 elif len(args)==2:
795 bkms[args[0]] = args[1]
793 bkms[args[0]] = args[1]
796 self.shell.db['bookmarks'] = bkms
794 self.shell.db['bookmarks'] = bkms
797
795
798 @line_magic
796 @line_magic
799 def pycat(self, parameter_s=''):
797 def pycat(self, parameter_s=''):
800 """Show a syntax-highlighted file through a pager.
798 """Show a syntax-highlighted file through a pager.
801
799
802 This magic is similar to the cat utility, but it will assume the file
800 This magic is similar to the cat utility, but it will assume the file
803 to be Python source and will show it with syntax highlighting.
801 to be Python source and will show it with syntax highlighting.
804
802
805 This magic command can either take a local filename, an url,
803 This magic command can either take a local filename, an url,
806 an history range (see %history) or a macro as argument.
804 an history range (see %history) or a macro as argument.
807
805
808 If no parameter is given, prints out history of current session up to
806 If no parameter is given, prints out history of current session up to
809 this point. ::
807 this point. ::
810
808
811 %pycat myscript.py
809 %pycat myscript.py
812 %pycat 7-27
810 %pycat 7-27
813 %pycat myMacro
811 %pycat myMacro
814 %pycat http://www.example.com/myscript.py
812 %pycat http://www.example.com/myscript.py
815 """
813 """
816 try:
814 try:
817 cont = self.shell.find_user_code(parameter_s, skip_encoding_cookie=False)
815 cont = self.shell.find_user_code(parameter_s, skip_encoding_cookie=False)
818 except (ValueError, IOError):
816 except (ValueError, IOError):
819 print("Error: no such file, variable, URL, history range or macro")
817 print("Error: no such file, variable, URL, history range or macro")
820 return
818 return
821
819
822 page.page(self.shell.pycolorize(source_to_unicode(cont)))
820 page.page(self.shell.pycolorize(source_to_unicode(cont)))
823
821
824 @magic_arguments.magic_arguments()
822 @magic_arguments.magic_arguments()
825 @magic_arguments.argument(
823 @magic_arguments.argument(
826 '-a', '--append', action='store_true', default=False,
824 '-a', '--append', action='store_true', default=False,
827 help='Append contents of the cell to an existing file. '
825 help='Append contents of the cell to an existing file. '
828 'The file will be created if it does not exist.'
826 'The file will be created if it does not exist.'
829 )
827 )
830 @magic_arguments.argument(
828 @magic_arguments.argument(
831 'filename', type=str,
829 'filename', type=str,
832 help='file to write'
830 help='file to write'
833 )
831 )
834 @cell_magic
832 @cell_magic
835 def writefile(self, line, cell):
833 def writefile(self, line, cell):
836 """Write the contents of the cell to a file.
834 """Write the contents of the cell to a file.
837
835
838 The file will be overwritten unless the -a (--append) flag is specified.
836 The file will be overwritten unless the -a (--append) flag is specified.
839 """
837 """
840 args = magic_arguments.parse_argstring(self.writefile, line)
838 args = magic_arguments.parse_argstring(self.writefile, line)
841 if re.match(r'^(\'.*\')|(".*")$', args.filename):
839 if re.match(r'^(\'.*\')|(".*")$', args.filename):
842 filename = os.path.expanduser(args.filename[1:-1])
840 filename = os.path.expanduser(args.filename[1:-1])
843 else:
841 else:
844 filename = os.path.expanduser(args.filename)
842 filename = os.path.expanduser(args.filename)
845
843
846 if os.path.exists(filename):
844 if os.path.exists(filename):
847 if args.append:
845 if args.append:
848 print("Appending to %s" % filename)
846 print("Appending to %s" % filename)
849 else:
847 else:
850 print("Overwriting %s" % filename)
848 print("Overwriting %s" % filename)
851 else:
849 else:
852 print("Writing %s" % filename)
850 print("Writing %s" % filename)
853
851
854 mode = 'a' if args.append else 'w'
852 mode = 'a' if args.append else 'w'
855 with io.open(filename, mode, encoding='utf-8') as f:
853 with io.open(filename, mode, encoding='utf-8') as f:
856 f.write(cell)
854 f.write(cell)
@@ -1,375 +1,375 b''
1 """Magic functions for running cells in various scripts."""
1 """Magic functions for running cells in various scripts."""
2
2
3 # Copyright (c) IPython Development Team.
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
4 # Distributed under the terms of the Modified BSD License.
5
5
6 import asyncio
6 import asyncio
7 import atexit
7 import atexit
8 import errno
8 import errno
9 import functools
9 import functools
10 import os
10 import os
11 import signal
11 import signal
12 import sys
12 import sys
13 import time
13 import time
14 from contextlib import contextmanager
14 from contextlib import contextmanager
15 from subprocess import CalledProcessError
15 from subprocess import CalledProcessError
16
16
17 from traitlets import Dict, List, default
17 from traitlets import Dict, List, default
18
18
19 from IPython.core import magic_arguments
19 from IPython.core import magic_arguments
20 from IPython.core.magic import Magics, cell_magic, line_magic, magics_class
20 from IPython.core.magic import Magics, cell_magic, line_magic, magics_class
21 from IPython.lib.backgroundjobs import BackgroundJobManager
21 from IPython.lib.backgroundjobs import BackgroundJobManager
22 from IPython.utils.process import arg_split
22 from IPython.utils.process import arg_split
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Magic implementation classes
25 # Magic implementation classes
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 def script_args(f):
28 def script_args(f):
29 """single decorator for adding script args"""
29 """single decorator for adding script args"""
30 args = [
30 args = [
31 magic_arguments.argument(
31 magic_arguments.argument(
32 '--out', type=str,
32 '--out', type=str,
33 help="""The variable in which to store stdout from the script.
33 help="""The variable in which to store stdout from the script.
34 If the script is backgrounded, this will be the stdout *pipe*,
34 If the script is backgrounded, this will be the stdout *pipe*,
35 instead of the stderr text itself and will not be auto closed.
35 instead of the stderr text itself and will not be auto closed.
36 """
36 """
37 ),
37 ),
38 magic_arguments.argument(
38 magic_arguments.argument(
39 '--err', type=str,
39 '--err', type=str,
40 help="""The variable in which to store stderr from the script.
40 help="""The variable in which to store stderr from the script.
41 If the script is backgrounded, this will be the stderr *pipe*,
41 If the script is backgrounded, this will be the stderr *pipe*,
42 instead of the stderr text itself and will not be autoclosed.
42 instead of the stderr text itself and will not be autoclosed.
43 """
43 """
44 ),
44 ),
45 magic_arguments.argument(
45 magic_arguments.argument(
46 '--bg', action="store_true",
46 '--bg', action="store_true",
47 help="""Whether to run the script in the background.
47 help="""Whether to run the script in the background.
48 If given, the only way to see the output of the command is
48 If given, the only way to see the output of the command is
49 with --out/err.
49 with --out/err.
50 """
50 """
51 ),
51 ),
52 magic_arguments.argument(
52 magic_arguments.argument(
53 '--proc', type=str,
53 '--proc', type=str,
54 help="""The variable in which to store Popen instance.
54 help="""The variable in which to store Popen instance.
55 This is used only when --bg option is given.
55 This is used only when --bg option is given.
56 """
56 """
57 ),
57 ),
58 magic_arguments.argument(
58 magic_arguments.argument(
59 '--no-raise-error', action="store_false", dest='raise_error',
59 '--no-raise-error', action="store_false", dest='raise_error',
60 help="""Whether you should raise an error message in addition to
60 help="""Whether you should raise an error message in addition to
61 a stream on stderr if you get a nonzero exit code.
61 a stream on stderr if you get a nonzero exit code.
62 """
62 """
63 )
63 )
64 ]
64 ]
65 for arg in args:
65 for arg in args:
66 f = arg(f)
66 f = arg(f)
67 return f
67 return f
68
68
69
69
70 @contextmanager
70 @contextmanager
71 def safe_watcher():
71 def safe_watcher():
72 if sys.platform == "win32":
72 if sys.platform == "win32":
73 yield
73 yield
74 return
74 return
75
75
76 from asyncio import SafeChildWatcher
76 from asyncio import SafeChildWatcher
77
77
78 policy = asyncio.get_event_loop_policy()
78 policy = asyncio.get_event_loop_policy()
79 old_watcher = policy.get_child_watcher()
79 old_watcher = policy.get_child_watcher()
80 if isinstance(old_watcher, SafeChildWatcher):
80 if isinstance(old_watcher, SafeChildWatcher):
81 yield
81 yield
82 return
82 return
83
83
84 try:
84 try:
85 loop = policy.get_event_loop()
85 loop = policy.get_event_loop()
86 if loop.is_closed():
86 if loop.is_closed():
87 raise RuntimeError("open a new one")
87 raise RuntimeError("open a new one")
88 except RuntimeError:
88 except RuntimeError:
89 # closed loop, make a new one
89 # closed loop, make a new one
90 loop = policy.new_event_loop()
90 loop = policy.new_event_loop()
91 policy.set_event_loop(loop)
91 policy.set_event_loop(loop)
92
92
93 try:
93 try:
94 watcher = asyncio.SafeChildWatcher()
94 watcher = asyncio.SafeChildWatcher()
95 watcher.attach_loop(loop)
95 watcher.attach_loop(loop)
96 policy.set_child_watcher(watcher)
96 policy.set_child_watcher(watcher)
97 yield
97 yield
98 finally:
98 finally:
99 watcher.close()
99 watcher.close()
100 policy.set_child_watcher(old_watcher)
100 policy.set_child_watcher(old_watcher)
101
101
102
102
103 def dec_safe_watcher(fun):
103 def dec_safe_watcher(fun):
104 @functools.wraps(fun)
104 @functools.wraps(fun)
105 def _inner(*args, **kwargs):
105 def _inner(*args, **kwargs):
106 with safe_watcher():
106 with safe_watcher():
107 return fun(*args, **kwargs)
107 return fun(*args, **kwargs)
108
108
109 return _inner
109 return _inner
110
110
111
111
112 @magics_class
112 @magics_class
113 class ScriptMagics(Magics):
113 class ScriptMagics(Magics):
114 """Magics for talking to scripts
114 """Magics for talking to scripts
115
115
116 This defines a base `%%script` cell magic for running a cell
116 This defines a base `%%script` cell magic for running a cell
117 with a program in a subprocess, and registers a few top-level
117 with a program in a subprocess, and registers a few top-level
118 magics that call %%script with common interpreters.
118 magics that call %%script with common interpreters.
119 """
119 """
120 script_magics = List(
120 script_magics = List(
121 help="""Extra script cell magics to define
121 help="""Extra script cell magics to define
122
122
123 This generates simple wrappers of `%%script foo` as `%%foo`.
123 This generates simple wrappers of `%%script foo` as `%%foo`.
124
124
125 If you want to add script magics that aren't on your path,
125 If you want to add script magics that aren't on your path,
126 specify them in script_paths
126 specify them in script_paths
127 """,
127 """,
128 ).tag(config=True)
128 ).tag(config=True)
129 @default('script_magics')
129 @default('script_magics')
130 def _script_magics_default(self):
130 def _script_magics_default(self):
131 """default to a common list of programs"""
131 """default to a common list of programs"""
132
132
133 defaults = [
133 defaults = [
134 'sh',
134 'sh',
135 'bash',
135 'bash',
136 'perl',
136 'perl',
137 'ruby',
137 'ruby',
138 'python',
138 'python',
139 'python2',
139 'python2',
140 'python3',
140 'python3',
141 'pypy',
141 'pypy',
142 ]
142 ]
143 if os.name == 'nt':
143 if os.name == 'nt':
144 defaults.extend([
144 defaults.extend([
145 'cmd',
145 'cmd',
146 ])
146 ])
147
147
148 return defaults
148 return defaults
149
149
150 script_paths = Dict(
150 script_paths = Dict(
151 help="""Dict mapping short 'ruby' names to full paths, such as '/opt/secret/bin/ruby'
151 help="""Dict mapping short 'ruby' names to full paths, such as '/opt/secret/bin/ruby'
152
152
153 Only necessary for items in script_magics where the default path will not
153 Only necessary for items in script_magics where the default path will not
154 find the right interpreter.
154 find the right interpreter.
155 """
155 """
156 ).tag(config=True)
156 ).tag(config=True)
157
157
158 def __init__(self, shell=None):
158 def __init__(self, shell=None):
159 super(ScriptMagics, self).__init__(shell=shell)
159 super(ScriptMagics, self).__init__(shell=shell)
160 self._generate_script_magics()
160 self._generate_script_magics()
161 self.job_manager = BackgroundJobManager()
161 self.job_manager = BackgroundJobManager()
162 self.bg_processes = []
162 self.bg_processes = []
163 atexit.register(self.kill_bg_processes)
163 atexit.register(self.kill_bg_processes)
164
164
165 def __del__(self):
165 def __del__(self):
166 self.kill_bg_processes()
166 self.kill_bg_processes()
167
167
168 def _generate_script_magics(self):
168 def _generate_script_magics(self):
169 cell_magics = self.magics['cell']
169 cell_magics = self.magics['cell']
170 for name in self.script_magics:
170 for name in self.script_magics:
171 cell_magics[name] = self._make_script_magic(name)
171 cell_magics[name] = self._make_script_magic(name)
172
172
173 def _make_script_magic(self, name):
173 def _make_script_magic(self, name):
174 """make a named magic, that calls %%script with a particular program"""
174 """make a named magic, that calls %%script with a particular program"""
175 # expand to explicit path if necessary:
175 # expand to explicit path if necessary:
176 script = self.script_paths.get(name, name)
176 script = self.script_paths.get(name, name)
177
177
178 @magic_arguments.magic_arguments()
178 @magic_arguments.magic_arguments()
179 @script_args
179 @script_args
180 def named_script_magic(line, cell):
180 def named_script_magic(line, cell):
181 # if line, add it as cl-flags
181 # if line, add it as cl-flags
182 if line:
182 if line:
183 line = "%s %s" % (script, line)
183 line = "%s %s" % (script, line)
184 else:
184 else:
185 line = script
185 line = script
186 return self.shebang(line, cell)
186 return self.shebang(line, cell)
187
187
188 # write a basic docstring:
188 # write a basic docstring:
189 named_script_magic.__doc__ = \
189 named_script_magic.__doc__ = \
190 """%%{name} script magic
190 """%%{name} script magic
191
191
192 Run cells with {script} in a subprocess.
192 Run cells with {script} in a subprocess.
193
193
194 This is a shortcut for `%%script {script}`
194 This is a shortcut for `%%script {script}`
195 """.format(**locals())
195 """.format(**locals())
196
196
197 return named_script_magic
197 return named_script_magic
198
198
199 @magic_arguments.magic_arguments()
199 @magic_arguments.magic_arguments()
200 @script_args
200 @script_args
201 @cell_magic("script")
201 @cell_magic("script")
202 @dec_safe_watcher
202 @dec_safe_watcher
203 def shebang(self, line, cell):
203 def shebang(self, line, cell):
204 """Run a cell via a shell command
204 """Run a cell via a shell command
205
205
206 The `%%script` line is like the #! line of script,
206 The `%%script` line is like the #! line of script,
207 specifying a program (bash, perl, ruby, etc.) with which to run.
207 specifying a program (bash, perl, ruby, etc.) with which to run.
208
208
209 The rest of the cell is run by that program.
209 The rest of the cell is run by that program.
210
210
211 Examples
211 Examples
212 --------
212 --------
213 ::
213 ::
214
214
215 In [1]: %%script bash
215 In [1]: %%script bash
216 ...: for i in 1 2 3; do
216 ...: for i in 1 2 3; do
217 ...: echo $i
217 ...: echo $i
218 ...: done
218 ...: done
219 1
219 1
220 2
220 2
221 3
221 3
222 """
222 """
223
223
224 async def _handle_stream(stream, stream_arg, file_object):
224 async def _handle_stream(stream, stream_arg, file_object):
225 while True:
225 while True:
226 line = (await stream.readline()).decode("utf8")
226 line = (await stream.readline()).decode("utf8")
227 if not line:
227 if not line:
228 break
228 break
229 if stream_arg:
229 if stream_arg:
230 self.shell.user_ns[stream_arg] = line
230 self.shell.user_ns[stream_arg] = line
231 else:
231 else:
232 file_object.write(line)
232 file_object.write(line)
233 file_object.flush()
233 file_object.flush()
234
234
235 async def _stream_communicate(process, cell):
235 async def _stream_communicate(process, cell):
236 process.stdin.write(cell)
236 process.stdin.write(cell)
237 process.stdin.close()
237 process.stdin.close()
238 stdout_task = asyncio.create_task(
238 stdout_task = asyncio.create_task(
239 _handle_stream(process.stdout, args.out, sys.stdout)
239 _handle_stream(process.stdout, args.out, sys.stdout)
240 )
240 )
241 stderr_task = asyncio.create_task(
241 stderr_task = asyncio.create_task(
242 _handle_stream(process.stderr, args.err, sys.stderr)
242 _handle_stream(process.stderr, args.err, sys.stderr)
243 )
243 )
244 await asyncio.wait([stdout_task, stderr_task])
244 await asyncio.wait([stdout_task, stderr_task])
245 await process.wait()
245 await process.wait()
246
246
247 policy = asyncio.get_event_loop_policy()
247 policy = asyncio.get_event_loop_policy()
248 if sys.platform.startswith("win") and not isinstance(
248 if sys.platform.startswith("win") and not isinstance(
249 policy, asyncio.WindowsProactorEventLoopPolicy
249 policy, asyncio.WindowsProactorEventLoopPolicy
250 ):
250 ):
251 # _do not_ overwrite the current policy
251 # _do not_ overwrite the current policy
252 policy = asyncio.WindowsProactorEventLoopPolicy()
252 policy = asyncio.WindowsProactorEventLoopPolicy()
253
253
254 try:
254 try:
255 loop = policy.get_event_loop()
255 loop = policy.get_event_loop()
256 except RuntimeError:
256 except RuntimeError:
257 # closed loop, make a new one
257 # closed loop, make a new one
258 loop = policy.new_event_loop()
258 loop = policy.new_event_loop()
259 policy.set_event_loop(loop)
259 policy.set_event_loop(loop)
260 argv = arg_split(line, posix=not sys.platform.startswith("win"))
260 argv = arg_split(line, posix=not sys.platform.startswith("win"))
261 args, cmd = self.shebang.parser.parse_known_args(argv)
261 args, cmd = self.shebang.parser.parse_known_args(argv)
262 try:
262 try:
263 p = loop.run_until_complete(
263 p = loop.run_until_complete(
264 asyncio.create_subprocess_exec(
264 asyncio.create_subprocess_exec(
265 *cmd,
265 *cmd,
266 stdout=asyncio.subprocess.PIPE,
266 stdout=asyncio.subprocess.PIPE,
267 stderr=asyncio.subprocess.PIPE,
267 stderr=asyncio.subprocess.PIPE,
268 stdin=asyncio.subprocess.PIPE,
268 stdin=asyncio.subprocess.PIPE,
269 )
269 )
270 )
270 )
271 except OSError as e:
271 except OSError as e:
272 if e.errno == errno.ENOENT:
272 if e.errno == errno.ENOENT:
273 print("Couldn't find program: %r" % cmd[0])
273 print("Couldn't find program: %r" % cmd[0])
274 return
274 return
275 else:
275 else:
276 raise
276 raise
277
277
278 if not cell.endswith('\n'):
278 if not cell.endswith('\n'):
279 cell += '\n'
279 cell += '\n'
280 cell = cell.encode('utf8', 'replace')
280 cell = cell.encode('utf8', 'replace')
281 if args.bg:
281 if args.bg:
282 self.bg_processes.append(p)
282 self.bg_processes.append(p)
283 self._gc_bg_processes()
283 self._gc_bg_processes()
284 to_close = []
284 to_close = []
285 if args.out:
285 if args.out:
286 self.shell.user_ns[args.out] = p.stdout
286 self.shell.user_ns[args.out] = p.stdout
287 else:
287 else:
288 to_close.append(p.stdout)
288 to_close.append(p.stdout)
289 if args.err:
289 if args.err:
290 self.shell.user_ns[args.err] = p.stderr
290 self.shell.user_ns[args.err] = p.stderr
291 else:
291 else:
292 to_close.append(p.stderr)
292 to_close.append(p.stderr)
293 self.job_manager.new(self._run_script, p, cell, to_close, daemon=True)
293 self.job_manager.new(self._run_script, p, cell, to_close, daemon=True)
294 if args.proc:
294 if args.proc:
295 self.shell.user_ns[args.proc] = p
295 self.shell.user_ns[args.proc] = p
296 return
296 return
297
297
298 try:
298 try:
299 loop.run_until_complete(_stream_communicate(p, cell))
299 loop.run_until_complete(_stream_communicate(p, cell))
300 except KeyboardInterrupt:
300 except KeyboardInterrupt:
301 try:
301 try:
302 p.send_signal(signal.SIGINT)
302 p.send_signal(signal.SIGINT)
303 time.sleep(0.1)
303 time.sleep(0.1)
304 if p.returncode is not None:
304 if p.returncode is not None:
305 print("Process is interrupted.")
305 print("Process is interrupted.")
306 return
306 return
307 p.terminate()
307 p.terminate()
308 time.sleep(0.1)
308 time.sleep(0.1)
309 if p.returncode is not None:
309 if p.returncode is not None:
310 print("Process is terminated.")
310 print("Process is terminated.")
311 return
311 return
312 p.kill()
312 p.kill()
313 print("Process is killed.")
313 print("Process is killed.")
314 except OSError:
314 except OSError:
315 pass
315 pass
316 except Exception as e:
316 except Exception as e:
317 print("Error while terminating subprocess (pid=%i): %s" % (p.pid, e))
317 print("Error while terminating subprocess (pid=%i): %s" % (p.pid, e))
318 return
318 return
319 if args.raise_error and p.returncode!=0:
319 if args.raise_error and p.returncode!=0:
320 # If we get here and p.returncode is still None, we must have
320 # If we get here and p.returncode is still None, we must have
321 # killed it but not yet seen its return code. We don't wait for it,
321 # killed it but not yet seen its return code. We don't wait for it,
322 # in case it's stuck in uninterruptible sleep. -9 = SIGKILL
322 # in case it's stuck in uninterruptible sleep. -9 = SIGKILL
323 rc = p.returncode or -9
323 rc = p.returncode or -9
324 raise CalledProcessError(rc, cell)
324 raise CalledProcessError(rc, cell)
325
325
326 shebang.__skip_doctest__ = os.name != "posix"
326 shebang.__skip_doctest__ = os.name != "posix"
327
327
328 def _run_script(self, p, cell, to_close):
328 def _run_script(self, p, cell, to_close):
329 """callback for running the script in the background"""
329 """callback for running the script in the background"""
330 p.stdin.write(cell)
330 p.stdin.write(cell)
331 p.stdin.close()
331 p.stdin.close()
332 for s in to_close:
332 for s in to_close:
333 s.close()
333 s.close()
334 p.wait()
334 p.wait()
335
335
336 @line_magic("killbgscripts")
336 @line_magic("killbgscripts")
337 def killbgscripts(self, _nouse_=''):
337 def killbgscripts(self, _nouse_=''):
338 """Kill all BG processes started by %%script and its family."""
338 """Kill all BG processes started by %%script and its family."""
339 self.kill_bg_processes()
339 self.kill_bg_processes()
340 print("All background processes were killed.")
340 print("All background processes were killed.")
341
341
342 def kill_bg_processes(self):
342 def kill_bg_processes(self):
343 """Kill all BG processes which are still running."""
343 """Kill all BG processes which are still running."""
344 if not self.bg_processes:
344 if not self.bg_processes:
345 return
345 return
346 for p in self.bg_processes:
346 for p in self.bg_processes:
347 if p.returncode is None:
347 if p.returncode is None:
348 try:
348 try:
349 p.send_signal(signal.SIGINT)
349 p.send_signal(signal.SIGINT)
350 except:
350 except:
351 pass
351 pass
352 time.sleep(0.1)
352 time.sleep(0.1)
353 self._gc_bg_processes()
353 self._gc_bg_processes()
354 if not self.bg_processes:
354 if not self.bg_processes:
355 return
355 return
356 for p in self.bg_processes:
356 for p in self.bg_processes:
357 if p.returncode is None:
357 if p.returncode is None:
358 try:
358 try:
359 p.terminate()
359 p.terminate()
360 except:
360 except:
361 pass
361 pass
362 time.sleep(0.1)
362 time.sleep(0.1)
363 self._gc_bg_processes()
363 self._gc_bg_processes()
364 if not self.bg_processes:
364 if not self.bg_processes:
365 return
365 return
366 for p in self.bg_processes:
366 for p in self.bg_processes:
367 if p.returncode is None:
367 if p.returncode is None:
368 try:
368 try:
369 p.kill()
369 p.kill()
370 except:
370 except:
371 pass
371 pass
372 self._gc_bg_processes()
372 self._gc_bg_processes()
373
373
374 def _gc_bg_processes(self):
374 def _gc_bg_processes(self):
375 self.bg_processes = [p for p in self.bg_processes if p.returncode is None]
375 self.bg_processes = [p for p in self.bg_processes if p.returncode is None]
@@ -1,108 +1,108 b''
1 [metadata]
1 [metadata]
2 name = ipython
2 name = ipython
3 version = attr: IPython.core.release.__version__
3 version = attr: IPython.core.release.__version__
4 url = https://ipython.org
4 url = https://ipython.org
5 description = IPython: Productive Interactive Computing
5 description = IPython: Productive Interactive Computing
6 long_description_content_type = text/x-rst
6 long_description_content_type = text/x-rst
7 long_description = IPython provides a rich toolkit to help you make the most out of using Python
7 long_description = IPython provides a rich toolkit to help you make the most out of using Python
8 interactively. Its main components are:
8 interactively. Its main components are:
9
9
10 * A powerful interactive Python shell
10 * A powerful interactive Python shell
11 * A `Jupyter <https://jupyter.org/>`_ kernel to work with Python code in Jupyter
11 * A `Jupyter <https://jupyter.org/>`_ kernel to work with Python code in Jupyter
12 notebooks and other interactive frontends.
12 notebooks and other interactive frontends.
13
13
14 The enhanced interactive Python shells have the following main features:
14 The enhanced interactive Python shells have the following main features:
15
15
16 * Comprehensive object introspection.
16 * Comprehensive object introspection.
17
17
18 * Input history, persistent across sessions.
18 * Input history, persistent across sessions.
19
19
20 * Caching of output results during a session with automatically generated
20 * Caching of output results during a session with automatically generated
21 references.
21 references.
22
22
23 * Extensible tab completion, with support by default for completion of python
23 * Extensible tab completion, with support by default for completion of python
24 variables and keywords, filenames and function keywords.
24 variables and keywords, filenames and function keywords.
25
25
26 * Extensible system of 'magic' commands for controlling the environment and
26 * Extensible system of 'magic' commands for controlling the environment and
27 performing many tasks related either to IPython or the operating system.
27 performing many tasks related either to IPython or the operating system.
28
28
29 * A rich configuration system with easy switching between different setups
29 * A rich configuration system with easy switching between different setups
30 (simpler than changing $PYTHONSTARTUP environment variables every time).
30 (simpler than changing $PYTHONSTARTUP environment variables every time).
31
31
32 * Session logging and reloading.
32 * Session logging and reloading.
33
33
34 * Extensible syntax processing for special purpose situations.
34 * Extensible syntax processing for special purpose situations.
35
35
36 * Access to the system shell with user-extensible alias system.
36 * Access to the system shell with user-extensible alias system.
37
37
38 * Easily embeddable in other Python programs and GUIs.
38 * Easily embeddable in other Python programs and GUIs.
39
39
40 * Integrated access to the pdb debugger and the Python profiler.
40 * Integrated access to the pdb debugger and the Python profiler.
41
41
42 The latest development version is always available from IPython's `GitHub
42 The latest development version is always available from IPython's `GitHub
43 site <http://github.com/ipython>`_.
43 site <http://github.com/ipython>`_.
44
44
45 license_file = LICENSE
45 license_file = LICENSE
46 project_urls =
46 project_urls =
47 Documentation = https://ipython.readthedocs.io/
47 Documentation = https://ipython.readthedocs.io/
48 Funding = https://numfocus.org/
48 Funding = https://numfocus.org/
49 Source = https://github.com/ipython/ipython
49 Source = https://github.com/ipython/ipython
50 Tracker = https://github.com/ipython/ipython/issues
50 Tracker = https://github.com/ipython/ipython/issues
51 keywords = Interactive, Interpreter, Shell, Embedding
51 keywords = Interactive, Interpreter, Shell, Embedding
52 platforms = Linux, Mac OSX, Windows
52 platforms = Linux, Mac OSX, Windows
53 classifiers =
53 classifiers =
54 Framework :: IPython
54 Framework :: IPython
55 Intended Audience :: Developers
55 Intended Audience :: Developers
56 Intended Audience :: Science/Research
56 Intended Audience :: Science/Research
57 License :: OSI Approved :: BSD License
57 License :: OSI Approved :: BSD License
58 Programming Language :: Python
58 Programming Language :: Python
59 Programming Language :: Python :: 3
59 Programming Language :: Python :: 3
60 Programming Language :: Python :: 3 :: Only
60 Programming Language :: Python :: 3 :: Only
61 Topic :: System :: Shell
61 Topic :: System :: Shell
62
62
63
63
64 [options]
64 [options]
65 packages = find:
65 packages = find:
66 python_requires = >=3.8
66 python_requires = >=3.8
67 zip_safe = False
67 zip_safe = False
68 install_requires =
68 install_requires =
69 setuptools>=18.5
69 setuptools>=18.5
70 jedi>=0.16
70 jedi>=0.16
71 decorator
71 decorator
72 pickleshare
72 pickleshare
73 traitlets>=5
73 traitlets>=5
74 prompt_toolkit>=2.0.0,<3.1.0,!=3.0.0,!=3.0.1
74 prompt_toolkit>=2.0.0,<3.1.0,!=3.0.0,!=3.0.1
75 pygments
75 pygments
76 backcall
76 backcall
77 stack_data
77 stack_data
78 matplotlib-inline
78 matplotlib-inline
79 pexpect>4.3; sys_platform != "win32"
79 pexpect>4.3; sys_platform != "win32"
80 appnope; sys_platform == "darwin"
80 appnope; sys_platform == "darwin"
81 colorama; sys_platform == "win32"
81 colorama; sys_platform == "win32"
82
82
83 [options.packages.find]
83 [options.packages.find]
84 exclude =
84 exclude =
85 setupext
85 setupext
86
86
87 [options.package_data]
87 [options.package_data]
88 IPython.core = profile/README*
88 IPython.core = profile/README*
89 IPython.core.tests = *.png, *.jpg, daft_extension/*.py
89 IPython.core.tests = *.png, *.jpg, daft_extension/*.py
90 IPython.lib.tests = *.wav
90 IPython.lib.tests = *.wav
91 IPython.testing.plugin = *.txt
91 IPython.testing.plugin = *.txt
92
92
93 [options.entry_points]
93 [options.entry_points]
94 console_scripts =
94 console_scripts =
95 ipython = IPython:start_ipython
95 ipython = IPython:start_ipython
96 ipython3 = IPython:start_ipython
96 ipython3 = IPython:start_ipython
97 pygments.lexers =
97 pygments.lexers =
98 ipythonconsole = IPython.lib.lexers:IPythonConsoleLexer
98 ipythonconsole = IPython.lib.lexers:IPythonConsoleLexer
99 ipython = IPython.lib.lexers:IPythonLexer
99 ipython = IPython.lib.lexers:IPythonLexer
100 ipython3 = IPython.lib.lexers:IPython3Lexer
100 ipython3 = IPython.lib.lexers:IPython3Lexer
101
101
102 [velin]
102 [velin]
103 ignore_patterns =
103 ignore_patterns =
104 IPython/core/tests,
104 IPython/core/tests
105 IPython/testing
105 IPython/testing
106
106
107 [tool.black]
107 [tool.black]
108 exclude = 'timing\.py'
108 exclude = 'timing\.py'
General Comments 0
You need to be logged in to leave comments. Login now