##// END OF EJS Templates
Fix backtics to be RST-formatted, not markdown.
Fernando Perez -
Show More
@@ -1,1517 +1,1517 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 gc
11 import gc
12 import itertools
12 import itertools
13 import os
13 import os
14 import shlex
14 import shlex
15 import sys
15 import sys
16 import time
16 import time
17 import timeit
17 import timeit
18 import math
18 import math
19 import re
19 import re
20 from pdb import Restart
20 from pdb import Restart
21
21
22 import cProfile as profile
22 import cProfile as profile
23 import pstats
23 import pstats
24
24
25 from IPython.core import oinspect
25 from IPython.core import oinspect
26 from IPython.core import magic_arguments
26 from IPython.core import magic_arguments
27 from IPython.core import page
27 from IPython.core import page
28 from IPython.core.error import UsageError
28 from IPython.core.error import UsageError
29 from IPython.core.macro import Macro
29 from IPython.core.macro import Macro
30 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
30 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
31 line_cell_magic, on_off, needs_local_scope,
31 line_cell_magic, on_off, needs_local_scope,
32 no_var_expand)
32 no_var_expand)
33 from IPython.testing.skipdoctest import skip_doctest
33 from IPython.testing.skipdoctest import skip_doctest
34 from IPython.utils.contexts import preserve_keys
34 from IPython.utils.contexts import preserve_keys
35 from IPython.utils.capture import capture_output
35 from IPython.utils.capture import capture_output
36 from IPython.utils.ipstruct import Struct
36 from IPython.utils.ipstruct import Struct
37 from IPython.utils.module_paths import find_mod
37 from IPython.utils.module_paths import find_mod
38 from IPython.utils.path import get_py_filename, shellglob
38 from IPython.utils.path import get_py_filename, shellglob
39 from IPython.utils.timing import clock, clock2
39 from IPython.utils.timing import clock, clock2
40 from warnings import warn
40 from warnings import warn
41 from logging import error
41 from logging import error
42 from pathlib import Path
42 from pathlib import Path
43 from io import StringIO
43 from io import StringIO
44 from pathlib import Path
44 from pathlib import Path
45
45
46 if sys.version_info > (3,8):
46 if sys.version_info > (3,8):
47 from ast import Module
47 from ast import Module
48 else :
48 else :
49 # mock the new API, ignore second argument
49 # mock the new API, ignore second argument
50 # see https://github.com/ipython/ipython/issues/11590
50 # see https://github.com/ipython/ipython/issues/11590
51 from ast import Module as OriginalModule
51 from ast import Module as OriginalModule
52 Module = lambda nodelist, type_ignores: OriginalModule(nodelist)
52 Module = lambda nodelist, type_ignores: OriginalModule(nodelist)
53
53
54
54
55 #-----------------------------------------------------------------------------
55 #-----------------------------------------------------------------------------
56 # Magic implementation classes
56 # Magic implementation classes
57 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
58
58
59
59
60 class TimeitResult(object):
60 class TimeitResult(object):
61 """
61 """
62 Object returned by the timeit magic with info about the run.
62 Object returned by the timeit magic with info about the run.
63
63
64 Contains the following attributes :
64 Contains the following attributes :
65
65
66 loops: (int) number of loops done per measurement
66 loops: (int) number of loops done per measurement
67 repeat: (int) number of times the measurement has been repeated
67 repeat: (int) number of times the measurement has been repeated
68 best: (float) best execution time / number
68 best: (float) best execution time / number
69 all_runs: (list of float) execution time of each run (in s)
69 all_runs: (list of float) execution time of each run (in s)
70 compile_time: (float) time of statement compilation (s)
70 compile_time: (float) time of statement compilation (s)
71
71
72 """
72 """
73 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
73 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
74 self.loops = loops
74 self.loops = loops
75 self.repeat = repeat
75 self.repeat = repeat
76 self.best = best
76 self.best = best
77 self.worst = worst
77 self.worst = worst
78 self.all_runs = all_runs
78 self.all_runs = all_runs
79 self.compile_time = compile_time
79 self.compile_time = compile_time
80 self._precision = precision
80 self._precision = precision
81 self.timings = [ dt / self.loops for dt in all_runs]
81 self.timings = [ dt / self.loops for dt in all_runs]
82
82
83 @property
83 @property
84 def average(self):
84 def average(self):
85 return math.fsum(self.timings) / len(self.timings)
85 return math.fsum(self.timings) / len(self.timings)
86
86
87 @property
87 @property
88 def stdev(self):
88 def stdev(self):
89 mean = self.average
89 mean = self.average
90 return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5
90 return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5
91
91
92 def __str__(self):
92 def __str__(self):
93 pm = '+-'
93 pm = '+-'
94 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
94 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
95 try:
95 try:
96 u'\xb1'.encode(sys.stdout.encoding)
96 u'\xb1'.encode(sys.stdout.encoding)
97 pm = u'\xb1'
97 pm = u'\xb1'
98 except:
98 except:
99 pass
99 pass
100 return (
100 return (
101 u"{mean} {pm} {std} per loop (mean {pm} std. dev. of {runs} run{run_plural}, {loops} loop{loop_plural} each)"
101 u"{mean} {pm} {std} per loop (mean {pm} std. dev. of {runs} run{run_plural}, {loops} loop{loop_plural} each)"
102 .format(
102 .format(
103 pm = pm,
103 pm = pm,
104 runs = self.repeat,
104 runs = self.repeat,
105 loops = self.loops,
105 loops = self.loops,
106 loop_plural = "" if self.loops == 1 else "s",
106 loop_plural = "" if self.loops == 1 else "s",
107 run_plural = "" if self.repeat == 1 else "s",
107 run_plural = "" if self.repeat == 1 else "s",
108 mean = _format_time(self.average, self._precision),
108 mean = _format_time(self.average, self._precision),
109 std = _format_time(self.stdev, self._precision))
109 std = _format_time(self.stdev, self._precision))
110 )
110 )
111
111
112 def _repr_pretty_(self, p , cycle):
112 def _repr_pretty_(self, p , cycle):
113 unic = self.__str__()
113 unic = self.__str__()
114 p.text(u'<TimeitResult : '+unic+u'>')
114 p.text(u'<TimeitResult : '+unic+u'>')
115
115
116
116
117 class TimeitTemplateFiller(ast.NodeTransformer):
117 class TimeitTemplateFiller(ast.NodeTransformer):
118 """Fill in the AST template for timing execution.
118 """Fill in the AST template for timing execution.
119
119
120 This is quite closely tied to the template definition, which is in
120 This is quite closely tied to the template definition, which is in
121 :meth:`ExecutionMagics.timeit`.
121 :meth:`ExecutionMagics.timeit`.
122 """
122 """
123 def __init__(self, ast_setup, ast_stmt):
123 def __init__(self, ast_setup, ast_stmt):
124 self.ast_setup = ast_setup
124 self.ast_setup = ast_setup
125 self.ast_stmt = ast_stmt
125 self.ast_stmt = ast_stmt
126
126
127 def visit_FunctionDef(self, node):
127 def visit_FunctionDef(self, node):
128 "Fill in the setup statement"
128 "Fill in the setup statement"
129 self.generic_visit(node)
129 self.generic_visit(node)
130 if node.name == "inner":
130 if node.name == "inner":
131 node.body[:1] = self.ast_setup.body
131 node.body[:1] = self.ast_setup.body
132
132
133 return node
133 return node
134
134
135 def visit_For(self, node):
135 def visit_For(self, node):
136 "Fill in the statement to be timed"
136 "Fill in the statement to be timed"
137 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
137 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
138 node.body = self.ast_stmt.body
138 node.body = self.ast_stmt.body
139 return node
139 return node
140
140
141
141
142 class Timer(timeit.Timer):
142 class Timer(timeit.Timer):
143 """Timer class that explicitly uses self.inner
143 """Timer class that explicitly uses self.inner
144
144
145 which is an undocumented implementation detail of CPython,
145 which is an undocumented implementation detail of CPython,
146 not shared by PyPy.
146 not shared by PyPy.
147 """
147 """
148 # Timer.timeit copied from CPython 3.4.2
148 # Timer.timeit copied from CPython 3.4.2
149 def timeit(self, number=timeit.default_number):
149 def timeit(self, number=timeit.default_number):
150 """Time 'number' executions of the main statement.
150 """Time 'number' executions of the main statement.
151
151
152 To be precise, this executes the setup statement once, and
152 To be precise, this executes the setup statement once, and
153 then returns the time it takes to execute the main statement
153 then returns the time it takes to execute the main statement
154 a number of times, as a float measured in seconds. The
154 a number of times, as a float measured in seconds. The
155 argument is the number of times through the loop, defaulting
155 argument is the number of times through the loop, defaulting
156 to one million. The main statement, the setup statement and
156 to one million. The main statement, the setup statement and
157 the timer function to be used are passed to the constructor.
157 the timer function to be used are passed to the constructor.
158 """
158 """
159 it = itertools.repeat(None, number)
159 it = itertools.repeat(None, number)
160 gcold = gc.isenabled()
160 gcold = gc.isenabled()
161 gc.disable()
161 gc.disable()
162 try:
162 try:
163 timing = self.inner(it, self.timer)
163 timing = self.inner(it, self.timer)
164 finally:
164 finally:
165 if gcold:
165 if gcold:
166 gc.enable()
166 gc.enable()
167 return timing
167 return timing
168
168
169
169
170 @magics_class
170 @magics_class
171 class ExecutionMagics(Magics):
171 class ExecutionMagics(Magics):
172 """Magics related to code execution, debugging, profiling, etc.
172 """Magics related to code execution, debugging, profiling, etc.
173
173
174 """
174 """
175
175
176 def __init__(self, shell):
176 def __init__(self, shell):
177 super(ExecutionMagics, self).__init__(shell)
177 super(ExecutionMagics, self).__init__(shell)
178 # Default execution function used to actually run user code.
178 # Default execution function used to actually run user code.
179 self.default_runner = None
179 self.default_runner = None
180
180
181 @skip_doctest
181 @skip_doctest
182 @no_var_expand
182 @no_var_expand
183 @line_cell_magic
183 @line_cell_magic
184 def prun(self, parameter_s='', cell=None):
184 def prun(self, parameter_s='', cell=None):
185
185
186 """Run a statement through the python code profiler.
186 """Run a statement through the python code profiler.
187
187
188 Usage, in line mode:
188 Usage, in line mode:
189 %prun [options] statement
189 %prun [options] statement
190
190
191 Usage, in cell mode:
191 Usage, in cell mode:
192 %%prun [options] [statement]
192 %%prun [options] [statement]
193 code...
193 code...
194 code...
194 code...
195
195
196 In cell mode, the additional code lines are appended to the (possibly
196 In cell mode, the additional code lines are appended to the (possibly
197 empty) statement in the first line. Cell mode allows you to easily
197 empty) statement in the first line. Cell mode allows you to easily
198 profile multiline blocks without having to put them in a separate
198 profile multiline blocks without having to put them in a separate
199 function.
199 function.
200
200
201 The given statement (which doesn't require quote marks) is run via the
201 The given statement (which doesn't require quote marks) is run via the
202 python profiler in a manner similar to the profile.run() function.
202 python profiler in a manner similar to the profile.run() function.
203 Namespaces are internally managed to work correctly; profile.run
203 Namespaces are internally managed to work correctly; profile.run
204 cannot be used in IPython because it makes certain assumptions about
204 cannot be used in IPython because it makes certain assumptions about
205 namespaces which do not hold under IPython.
205 namespaces which do not hold under IPython.
206
206
207 Options:
207 Options:
208
208
209 -l <limit>
209 -l <limit>
210 you can place restrictions on what or how much of the
210 you can place restrictions on what or how much of the
211 profile gets printed. The limit value can be:
211 profile gets printed. The limit value can be:
212
212
213 * A string: only information for function names containing this string
213 * A string: only information for function names containing this string
214 is printed.
214 is printed.
215
215
216 * An integer: only these many lines are printed.
216 * An integer: only these many lines are printed.
217
217
218 * A float (between 0 and 1): this fraction of the report is printed
218 * A float (between 0 and 1): this fraction of the report is printed
219 (for example, use a limit of 0.4 to see the topmost 40% only).
219 (for example, use a limit of 0.4 to see the topmost 40% only).
220
220
221 You can combine several limits with repeated use of the option. For
221 You can combine several limits with repeated use of the option. For
222 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
222 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
223 information about class constructors.
223 information about class constructors.
224
224
225 -r
225 -r
226 return the pstats.Stats object generated by the profiling. This
226 return the pstats.Stats object generated by the profiling. This
227 object has all the information about the profile in it, and you can
227 object has all the information about the profile in it, and you can
228 later use it for further analysis or in other functions.
228 later use it for further analysis or in other functions.
229
229
230 -s <key>
230 -s <key>
231 sort profile by given key. You can provide more than one key
231 sort profile by given key. You can provide more than one key
232 by using the option several times: '-s key1 -s key2 -s key3...'. The
232 by using the option several times: '-s key1 -s key2 -s key3...'. The
233 default sorting key is 'time'.
233 default sorting key is 'time'.
234
234
235 The following is copied verbatim from the profile documentation
235 The following is copied verbatim from the profile documentation
236 referenced below:
236 referenced below:
237
237
238 When more than one key is provided, additional keys are used as
238 When more than one key is provided, additional keys are used as
239 secondary criteria when the there is equality in all keys selected
239 secondary criteria when the there is equality in all keys selected
240 before them.
240 before them.
241
241
242 Abbreviations can be used for any key names, as long as the
242 Abbreviations can be used for any key names, as long as the
243 abbreviation is unambiguous. The following are the keys currently
243 abbreviation is unambiguous. The following are the keys currently
244 defined:
244 defined:
245
245
246 ============ =====================
246 ============ =====================
247 Valid Arg Meaning
247 Valid Arg Meaning
248 ============ =====================
248 ============ =====================
249 "calls" call count
249 "calls" call count
250 "cumulative" cumulative time
250 "cumulative" cumulative time
251 "file" file name
251 "file" file name
252 "module" file name
252 "module" file name
253 "pcalls" primitive call count
253 "pcalls" primitive call count
254 "line" line number
254 "line" line number
255 "name" function name
255 "name" function name
256 "nfl" name/file/line
256 "nfl" name/file/line
257 "stdname" standard name
257 "stdname" standard name
258 "time" internal time
258 "time" internal time
259 ============ =====================
259 ============ =====================
260
260
261 Note that all sorts on statistics are in descending order (placing
261 Note that all sorts on statistics are in descending order (placing
262 most time consuming items first), where as name, file, and line number
262 most time consuming items first), where as name, file, and line number
263 searches are in ascending order (i.e., alphabetical). The subtle
263 searches are in ascending order (i.e., alphabetical). The subtle
264 distinction between "nfl" and "stdname" is that the standard name is a
264 distinction between "nfl" and "stdname" is that the standard name is a
265 sort of the name as printed, which means that the embedded line
265 sort of the name as printed, which means that the embedded line
266 numbers get compared in an odd way. For example, lines 3, 20, and 40
266 numbers get compared in an odd way. For example, lines 3, 20, and 40
267 would (if the file names were the same) appear in the string order
267 would (if the file names were the same) appear in the string order
268 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
268 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
269 line numbers. In fact, sort_stats("nfl") is the same as
269 line numbers. In fact, sort_stats("nfl") is the same as
270 sort_stats("name", "file", "line").
270 sort_stats("name", "file", "line").
271
271
272 -T <filename>
272 -T <filename>
273 save profile results as shown on screen to a text
273 save profile results as shown on screen to a text
274 file. The profile is still shown on screen.
274 file. The profile is still shown on screen.
275
275
276 -D <filename>
276 -D <filename>
277 save (via dump_stats) profile statistics to given
277 save (via dump_stats) profile statistics to given
278 filename. This data is in a format understood by the pstats module, and
278 filename. This data is in a format understood by the pstats module, and
279 is generated by a call to the dump_stats() method of profile
279 is generated by a call to the dump_stats() method of profile
280 objects. The profile is still shown on screen.
280 objects. The profile is still shown on screen.
281
281
282 -q
282 -q
283 suppress output to the pager. Best used with -T and/or -D above.
283 suppress output to the pager. Best used with -T and/or -D above.
284
284
285 If you want to run complete programs under the profiler's control, use
285 If you want to run complete programs under the profiler's control, use
286 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
286 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
287 contains profiler specific options as described here.
287 contains profiler specific options as described here.
288
288
289 You can read the complete documentation for the profile module with::
289 You can read the complete documentation for the profile module with::
290
290
291 In [1]: import profile; profile.help()
291 In [1]: import profile; profile.help()
292
292
293 .. versionchanged:: 7.3
293 .. versionchanged:: 7.3
294 User variables are no longer expanded,
294 User variables are no longer expanded,
295 the magic line is always left unmodified.
295 the magic line is always left unmodified.
296
296
297 """
297 """
298 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
298 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
299 list_all=True, posix=False)
299 list_all=True, posix=False)
300 if cell is not None:
300 if cell is not None:
301 arg_str += '\n' + cell
301 arg_str += '\n' + cell
302 arg_str = self.shell.transform_cell(arg_str)
302 arg_str = self.shell.transform_cell(arg_str)
303 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
303 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
304
304
305 def _run_with_profiler(self, code, opts, namespace):
305 def _run_with_profiler(self, code, opts, namespace):
306 """
306 """
307 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
307 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
308
308
309 Parameters
309 Parameters
310 ----------
310 ----------
311 code : str
311 code : str
312 Code to be executed.
312 Code to be executed.
313 opts : Struct
313 opts : Struct
314 Options parsed by `self.parse_options`.
314 Options parsed by `self.parse_options`.
315 namespace : dict
315 namespace : dict
316 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
316 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
317
317
318 """
318 """
319
319
320 # Fill default values for unspecified options:
320 # Fill default values for unspecified options:
321 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
321 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
322
322
323 prof = profile.Profile()
323 prof = profile.Profile()
324 try:
324 try:
325 prof = prof.runctx(code, namespace, namespace)
325 prof = prof.runctx(code, namespace, namespace)
326 sys_exit = ''
326 sys_exit = ''
327 except SystemExit:
327 except SystemExit:
328 sys_exit = """*** SystemExit exception caught in code being profiled."""
328 sys_exit = """*** SystemExit exception caught in code being profiled."""
329
329
330 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
330 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
331
331
332 lims = opts.l
332 lims = opts.l
333 if lims:
333 if lims:
334 lims = [] # rebuild lims with ints/floats/strings
334 lims = [] # rebuild lims with ints/floats/strings
335 for lim in opts.l:
335 for lim in opts.l:
336 try:
336 try:
337 lims.append(int(lim))
337 lims.append(int(lim))
338 except ValueError:
338 except ValueError:
339 try:
339 try:
340 lims.append(float(lim))
340 lims.append(float(lim))
341 except ValueError:
341 except ValueError:
342 lims.append(lim)
342 lims.append(lim)
343
343
344 # Trap output.
344 # Trap output.
345 stdout_trap = StringIO()
345 stdout_trap = StringIO()
346 stats_stream = stats.stream
346 stats_stream = stats.stream
347 try:
347 try:
348 stats.stream = stdout_trap
348 stats.stream = stdout_trap
349 stats.print_stats(*lims)
349 stats.print_stats(*lims)
350 finally:
350 finally:
351 stats.stream = stats_stream
351 stats.stream = stats_stream
352
352
353 output = stdout_trap.getvalue()
353 output = stdout_trap.getvalue()
354 output = output.rstrip()
354 output = output.rstrip()
355
355
356 if 'q' not in opts:
356 if 'q' not in opts:
357 page.page(output)
357 page.page(output)
358 print(sys_exit, end=' ')
358 print(sys_exit, end=' ')
359
359
360 dump_file = opts.D[0]
360 dump_file = opts.D[0]
361 text_file = opts.T[0]
361 text_file = opts.T[0]
362 if dump_file:
362 if dump_file:
363 prof.dump_stats(dump_file)
363 prof.dump_stats(dump_file)
364 print(
364 print(
365 f"\n*** Profile stats marshalled to file {repr(dump_file)}.{sys_exit}"
365 f"\n*** Profile stats marshalled to file {repr(dump_file)}.{sys_exit}"
366 )
366 )
367 if text_file:
367 if text_file:
368 pfile = Path(text_file)
368 pfile = Path(text_file)
369 pfile.touch(exist_ok=True)
369 pfile.touch(exist_ok=True)
370 pfile.write_text(output)
370 pfile.write_text(output)
371
371
372 print(
372 print(
373 f"\n*** Profile printout saved to text file {repr(text_file)}.{sys_exit}"
373 f"\n*** Profile printout saved to text file {repr(text_file)}.{sys_exit}"
374 )
374 )
375
375
376 if 'r' in opts:
376 if 'r' in opts:
377 return stats
377 return stats
378
378
379 return None
379 return None
380
380
381 @line_magic
381 @line_magic
382 def pdb(self, parameter_s=''):
382 def pdb(self, parameter_s=''):
383 """Control the automatic calling of the pdb interactive debugger.
383 """Control the automatic calling of the pdb interactive debugger.
384
384
385 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
385 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
386 argument it works as a toggle.
386 argument it works as a toggle.
387
387
388 When an exception is triggered, IPython can optionally call the
388 When an exception is triggered, IPython can optionally call the
389 interactive pdb debugger after the traceback printout. %pdb toggles
389 interactive pdb debugger after the traceback printout. %pdb toggles
390 this feature on and off.
390 this feature on and off.
391
391
392 The initial state of this feature is set in your configuration
392 The initial state of this feature is set in your configuration
393 file (the option is ``InteractiveShell.pdb``).
393 file (the option is ``InteractiveShell.pdb``).
394
394
395 If you want to just activate the debugger AFTER an exception has fired,
395 If you want to just activate the debugger AFTER an exception has fired,
396 without having to type '%pdb on' and rerunning your code, you can use
396 without having to type '%pdb on' and rerunning your code, you can use
397 the %debug magic."""
397 the %debug magic."""
398
398
399 par = parameter_s.strip().lower()
399 par = parameter_s.strip().lower()
400
400
401 if par:
401 if par:
402 try:
402 try:
403 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
403 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
404 except KeyError:
404 except KeyError:
405 print ('Incorrect argument. Use on/1, off/0, '
405 print ('Incorrect argument. Use on/1, off/0, '
406 'or nothing for a toggle.')
406 'or nothing for a toggle.')
407 return
407 return
408 else:
408 else:
409 # toggle
409 # toggle
410 new_pdb = not self.shell.call_pdb
410 new_pdb = not self.shell.call_pdb
411
411
412 # set on the shell
412 # set on the shell
413 self.shell.call_pdb = new_pdb
413 self.shell.call_pdb = new_pdb
414 print('Automatic pdb calling has been turned',on_off(new_pdb))
414 print('Automatic pdb calling has been turned',on_off(new_pdb))
415
415
416 @skip_doctest
416 @skip_doctest
417 @magic_arguments.magic_arguments()
417 @magic_arguments.magic_arguments()
418 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
418 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
419 help="""
419 help="""
420 Set break point at LINE in FILE.
420 Set break point at LINE in FILE.
421 """
421 """
422 )
422 )
423 @magic_arguments.argument('statement', nargs='*',
423 @magic_arguments.argument('statement', nargs='*',
424 help="""
424 help="""
425 Code to run in debugger.
425 Code to run in debugger.
426 You can omit this in cell magic mode.
426 You can omit this in cell magic mode.
427 """
427 """
428 )
428 )
429 @no_var_expand
429 @no_var_expand
430 @line_cell_magic
430 @line_cell_magic
431 def debug(self, line='', cell=None):
431 def debug(self, line='', cell=None):
432 """Activate the interactive debugger.
432 """Activate the interactive debugger.
433
433
434 This magic command support two ways of activating debugger.
434 This magic command support two ways of activating debugger.
435 One is to activate debugger before executing code. This way, you
435 One is to activate debugger before executing code. This way, you
436 can set a break point, to step through the code from the point.
436 can set a break point, to step through the code from the point.
437 You can use this mode by giving statements to execute and optionally
437 You can use this mode by giving statements to execute and optionally
438 a breakpoint.
438 a breakpoint.
439
439
440 The other one is to activate debugger in post-mortem mode. You can
440 The other one is to activate debugger in post-mortem mode. You can
441 activate this mode simply running %debug without any argument.
441 activate this mode simply running %debug without any argument.
442 If an exception has just occurred, this lets you inspect its stack
442 If an exception has just occurred, this lets you inspect its stack
443 frames interactively. Note that this will always work only on the last
443 frames interactively. Note that this will always work only on the last
444 traceback that occurred, so you must call this quickly after an
444 traceback that occurred, so you must call this quickly after an
445 exception that you wish to inspect has fired, because if another one
445 exception that you wish to inspect has fired, because if another one
446 occurs, it clobbers the previous one.
446 occurs, it clobbers the previous one.
447
447
448 If you want IPython to automatically do this on every exception, see
448 If you want IPython to automatically do this on every exception, see
449 the %pdb magic for more details.
449 the %pdb magic for more details.
450
450
451 .. versionchanged:: 7.3
451 .. versionchanged:: 7.3
452 When running code, user variables are no longer expanded,
452 When running code, user variables are no longer expanded,
453 the magic line is always left unmodified.
453 the magic line is always left unmodified.
454
454
455 """
455 """
456 args = magic_arguments.parse_argstring(self.debug, line)
456 args = magic_arguments.parse_argstring(self.debug, line)
457
457
458 if not (args.breakpoint or args.statement or cell):
458 if not (args.breakpoint or args.statement or cell):
459 self._debug_post_mortem()
459 self._debug_post_mortem()
460 elif not (args.breakpoint or cell):
460 elif not (args.breakpoint or cell):
461 # If there is no breakpoints, the line is just code to execute
461 # If there is no breakpoints, the line is just code to execute
462 self._debug_exec(line, None)
462 self._debug_exec(line, None)
463 else:
463 else:
464 # Here we try to reconstruct the code from the output of
464 # Here we try to reconstruct the code from the output of
465 # parse_argstring. This might not work if the code has spaces
465 # parse_argstring. This might not work if the code has spaces
466 # For example this fails for `print("a b")`
466 # For example this fails for `print("a b")`
467 code = "\n".join(args.statement)
467 code = "\n".join(args.statement)
468 if cell:
468 if cell:
469 code += "\n" + cell
469 code += "\n" + cell
470 self._debug_exec(code, args.breakpoint)
470 self._debug_exec(code, args.breakpoint)
471
471
472 def _debug_post_mortem(self):
472 def _debug_post_mortem(self):
473 self.shell.debugger(force=True)
473 self.shell.debugger(force=True)
474
474
475 def _debug_exec(self, code, breakpoint):
475 def _debug_exec(self, code, breakpoint):
476 if breakpoint:
476 if breakpoint:
477 (filename, bp_line) = breakpoint.rsplit(':', 1)
477 (filename, bp_line) = breakpoint.rsplit(':', 1)
478 bp_line = int(bp_line)
478 bp_line = int(bp_line)
479 else:
479 else:
480 (filename, bp_line) = (None, None)
480 (filename, bp_line) = (None, None)
481 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
481 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
482
482
483 @line_magic
483 @line_magic
484 def tb(self, s):
484 def tb(self, s):
485 """Print the last traceback.
485 """Print the last traceback.
486
486
487 Optionally, specify an exception reporting mode, tuning the
487 Optionally, specify an exception reporting mode, tuning the
488 verbosity of the traceback. By default the currently-active exception
488 verbosity of the traceback. By default the currently-active exception
489 mode is used. See %xmode for changing exception reporting modes.
489 mode is used. See %xmode for changing exception reporting modes.
490
490
491 Valid modes: Plain, Context, Verbose, and Minimal.
491 Valid modes: Plain, Context, Verbose, and Minimal.
492 """
492 """
493 interactive_tb = self.shell.InteractiveTB
493 interactive_tb = self.shell.InteractiveTB
494 if s:
494 if s:
495 # Switch exception reporting mode for this one call.
495 # Switch exception reporting mode for this one call.
496 # Ensure it is switched back.
496 # Ensure it is switched back.
497 def xmode_switch_err(name):
497 def xmode_switch_err(name):
498 warn('Error changing %s exception modes.\n%s' %
498 warn('Error changing %s exception modes.\n%s' %
499 (name,sys.exc_info()[1]))
499 (name,sys.exc_info()[1]))
500
500
501 new_mode = s.strip().capitalize()
501 new_mode = s.strip().capitalize()
502 original_mode = interactive_tb.mode
502 original_mode = interactive_tb.mode
503 try:
503 try:
504 try:
504 try:
505 interactive_tb.set_mode(mode=new_mode)
505 interactive_tb.set_mode(mode=new_mode)
506 except Exception:
506 except Exception:
507 xmode_switch_err('user')
507 xmode_switch_err('user')
508 else:
508 else:
509 self.shell.showtraceback()
509 self.shell.showtraceback()
510 finally:
510 finally:
511 interactive_tb.set_mode(mode=original_mode)
511 interactive_tb.set_mode(mode=original_mode)
512 else:
512 else:
513 self.shell.showtraceback()
513 self.shell.showtraceback()
514
514
515 @skip_doctest
515 @skip_doctest
516 @line_magic
516 @line_magic
517 def run(self, parameter_s='', runner=None,
517 def run(self, parameter_s='', runner=None,
518 file_finder=get_py_filename):
518 file_finder=get_py_filename):
519 """Run the named file inside IPython as a program.
519 """Run the named file inside IPython as a program.
520
520
521 Usage::
521 Usage::
522
522
523 %run [-n -i -e -G]
523 %run [-n -i -e -G]
524 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
524 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
525 ( -m mod | filename ) [args]
525 ( -m mod | filename ) [args]
526
526
527 The filename argument should be either a pure Python script (with
527 The filename argument should be either a pure Python script (with
528 extension `.py`), or a file with custom IPython syntax (such as
528 extension ``.py``), or a file with custom IPython syntax (such as
529 magics). If the latter, the file can be either a script with `.ipy`
529 magics). If the latter, the file can be either a script with ``.ipy``
530 extension, or a Jupyter notebook with `.ipynb` extension. When running
530 extension, or a Jupyter notebook with ``.ipynb`` extension. When running
531 a Jupyter notebook, the output from print statements and other
531 a Jupyter notebook, the output from print statements and other
532 displayed objects will appear in the terminal (even matplotlib figures
532 displayed objects will appear in the terminal (even matplotlib figures
533 will open, if a terminal-compliant backend is being used). Note that,
533 will open, if a terminal-compliant backend is being used). Note that,
534 at the system command line, the `jupyter run` command offers similar
534 at the system command line, the ``jupyter run`` command offers similar
535 functionality for executing notebooks (albeit currently with some
535 functionality for executing notebooks (albeit currently with some
536 differences in supported options).
536 differences in supported options).
537
537
538 Parameters after the filename are passed as command-line arguments to
538 Parameters after the filename are passed as command-line arguments to
539 the program (put in sys.argv). Then, control returns to IPython's
539 the program (put in sys.argv). Then, control returns to IPython's
540 prompt.
540 prompt.
541
541
542 This is similar to running at a system prompt ``python file args``,
542 This is similar to running at a system prompt ``python file args``,
543 but with the advantage of giving you IPython's tracebacks, and of
543 but with the advantage of giving you IPython's tracebacks, and of
544 loading all variables into your interactive namespace for further use
544 loading all variables into your interactive namespace for further use
545 (unless -p is used, see below).
545 (unless -p is used, see below).
546
546
547 The file is executed in a namespace initially consisting only of
547 The file is executed in a namespace initially consisting only of
548 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
548 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
549 sees its environment as if it were being run as a stand-alone program
549 sees its environment as if it were being run as a stand-alone program
550 (except for sharing global objects such as previously imported
550 (except for sharing global objects such as previously imported
551 modules). But after execution, the IPython interactive namespace gets
551 modules). But after execution, the IPython interactive namespace gets
552 updated with all variables defined in the program (except for __name__
552 updated with all variables defined in the program (except for __name__
553 and sys.argv). This allows for very convenient loading of code for
553 and sys.argv). This allows for very convenient loading of code for
554 interactive work, while giving each program a 'clean sheet' to run in.
554 interactive work, while giving each program a 'clean sheet' to run in.
555
555
556 Arguments are expanded using shell-like glob match. Patterns
556 Arguments are expanded using shell-like glob match. Patterns
557 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
557 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
558 tilde '~' will be expanded into user's home directory. Unlike
558 tilde '~' will be expanded into user's home directory. Unlike
559 real shells, quotation does not suppress expansions. Use
559 real shells, quotation does not suppress expansions. Use
560 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
560 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
561 To completely disable these expansions, you can use -G flag.
561 To completely disable these expansions, you can use -G flag.
562
562
563 On Windows systems, the use of single quotes `'` when specifying
563 On Windows systems, the use of single quotes `'` when specifying
564 a file is not supported. Use double quotes `"`.
564 a file is not supported. Use double quotes `"`.
565
565
566 Options:
566 Options:
567
567
568 -n
568 -n
569 __name__ is NOT set to '__main__', but to the running file's name
569 __name__ is NOT set to '__main__', but to the running file's name
570 without extension (as python does under import). This allows running
570 without extension (as python does under import). This allows running
571 scripts and reloading the definitions in them without calling code
571 scripts and reloading the definitions in them without calling code
572 protected by an ``if __name__ == "__main__"`` clause.
572 protected by an ``if __name__ == "__main__"`` clause.
573
573
574 -i
574 -i
575 run the file in IPython's namespace instead of an empty one. This
575 run the file in IPython's namespace instead of an empty one. This
576 is useful if you are experimenting with code written in a text editor
576 is useful if you are experimenting with code written in a text editor
577 which depends on variables defined interactively.
577 which depends on variables defined interactively.
578
578
579 -e
579 -e
580 ignore sys.exit() calls or SystemExit exceptions in the script
580 ignore sys.exit() calls or SystemExit exceptions in the script
581 being run. This is particularly useful if IPython is being used to
581 being run. This is particularly useful if IPython is being used to
582 run unittests, which always exit with a sys.exit() call. In such
582 run unittests, which always exit with a sys.exit() call. In such
583 cases you are interested in the output of the test results, not in
583 cases you are interested in the output of the test results, not in
584 seeing a traceback of the unittest module.
584 seeing a traceback of the unittest module.
585
585
586 -t
586 -t
587 print timing information at the end of the run. IPython will give
587 print timing information at the end of the run. IPython will give
588 you an estimated CPU time consumption for your script, which under
588 you an estimated CPU time consumption for your script, which under
589 Unix uses the resource module to avoid the wraparound problems of
589 Unix uses the resource module to avoid the wraparound problems of
590 time.clock(). Under Unix, an estimate of time spent on system tasks
590 time.clock(). Under Unix, an estimate of time spent on system tasks
591 is also given (for Windows platforms this is reported as 0.0).
591 is also given (for Windows platforms this is reported as 0.0).
592
592
593 If -t is given, an additional ``-N<N>`` option can be given, where <N>
593 If -t is given, an additional ``-N<N>`` option can be given, where <N>
594 must be an integer indicating how many times you want the script to
594 must be an integer indicating how many times you want the script to
595 run. The final timing report will include total and per run results.
595 run. The final timing report will include total and per run results.
596
596
597 For example (testing the script uniq_stable.py)::
597 For example (testing the script uniq_stable.py)::
598
598
599 In [1]: run -t uniq_stable
599 In [1]: run -t uniq_stable
600
600
601 IPython CPU timings (estimated):
601 IPython CPU timings (estimated):
602 User : 0.19597 s.
602 User : 0.19597 s.
603 System: 0.0 s.
603 System: 0.0 s.
604
604
605 In [2]: run -t -N5 uniq_stable
605 In [2]: run -t -N5 uniq_stable
606
606
607 IPython CPU timings (estimated):
607 IPython CPU timings (estimated):
608 Total runs performed: 5
608 Total runs performed: 5
609 Times : Total Per run
609 Times : Total Per run
610 User : 0.910862 s, 0.1821724 s.
610 User : 0.910862 s, 0.1821724 s.
611 System: 0.0 s, 0.0 s.
611 System: 0.0 s, 0.0 s.
612
612
613 -d
613 -d
614 run your program under the control of pdb, the Python debugger.
614 run your program under the control of pdb, the Python debugger.
615 This allows you to execute your program step by step, watch variables,
615 This allows you to execute your program step by step, watch variables,
616 etc. Internally, what IPython does is similar to calling::
616 etc. Internally, what IPython does is similar to calling::
617
617
618 pdb.run('execfile("YOURFILENAME")')
618 pdb.run('execfile("YOURFILENAME")')
619
619
620 with a breakpoint set on line 1 of your file. You can change the line
620 with a breakpoint set on line 1 of your file. You can change the line
621 number for this automatic breakpoint to be <N> by using the -bN option
621 number for this automatic breakpoint to be <N> by using the -bN option
622 (where N must be an integer). For example::
622 (where N must be an integer). For example::
623
623
624 %run -d -b40 myscript
624 %run -d -b40 myscript
625
625
626 will set the first breakpoint at line 40 in myscript.py. Note that
626 will set the first breakpoint at line 40 in myscript.py. Note that
627 the first breakpoint must be set on a line which actually does
627 the first breakpoint must be set on a line which actually does
628 something (not a comment or docstring) for it to stop execution.
628 something (not a comment or docstring) for it to stop execution.
629
629
630 Or you can specify a breakpoint in a different file::
630 Or you can specify a breakpoint in a different file::
631
631
632 %run -d -b myotherfile.py:20 myscript
632 %run -d -b myotherfile.py:20 myscript
633
633
634 When the pdb debugger starts, you will see a (Pdb) prompt. You must
634 When the pdb debugger starts, you will see a (Pdb) prompt. You must
635 first enter 'c' (without quotes) to start execution up to the first
635 first enter 'c' (without quotes) to start execution up to the first
636 breakpoint.
636 breakpoint.
637
637
638 Entering 'help' gives information about the use of the debugger. You
638 Entering 'help' gives information about the use of the debugger. You
639 can easily see pdb's full documentation with "import pdb;pdb.help()"
639 can easily see pdb's full documentation with "import pdb;pdb.help()"
640 at a prompt.
640 at a prompt.
641
641
642 -p
642 -p
643 run program under the control of the Python profiler module (which
643 run program under the control of the Python profiler module (which
644 prints a detailed report of execution times, function calls, etc).
644 prints a detailed report of execution times, function calls, etc).
645
645
646 You can pass other options after -p which affect the behavior of the
646 You can pass other options after -p which affect the behavior of the
647 profiler itself. See the docs for %prun for details.
647 profiler itself. See the docs for %prun for details.
648
648
649 In this mode, the program's variables do NOT propagate back to the
649 In this mode, the program's variables do NOT propagate back to the
650 IPython interactive namespace (because they remain in the namespace
650 IPython interactive namespace (because they remain in the namespace
651 where the profiler executes them).
651 where the profiler executes them).
652
652
653 Internally this triggers a call to %prun, see its documentation for
653 Internally this triggers a call to %prun, see its documentation for
654 details on the options available specifically for profiling.
654 details on the options available specifically for profiling.
655
655
656 There is one special usage for which the text above doesn't apply:
656 There is one special usage for which the text above doesn't apply:
657 if the filename ends with .ipy[nb], the file is run as ipython script,
657 if the filename ends with .ipy[nb], the file is run as ipython script,
658 just as if the commands were written on IPython prompt.
658 just as if the commands were written on IPython prompt.
659
659
660 -m
660 -m
661 specify module name to load instead of script path. Similar to
661 specify module name to load instead of script path. Similar to
662 the -m option for the python interpreter. Use this option last if you
662 the -m option for the python interpreter. Use this option last if you
663 want to combine with other %run options. Unlike the python interpreter
663 want to combine with other %run options. Unlike the python interpreter
664 only source modules are allowed no .pyc or .pyo files.
664 only source modules are allowed no .pyc or .pyo files.
665 For example::
665 For example::
666
666
667 %run -m example
667 %run -m example
668
668
669 will run the example module.
669 will run the example module.
670
670
671 -G
671 -G
672 disable shell-like glob expansion of arguments.
672 disable shell-like glob expansion of arguments.
673
673
674 """
674 """
675
675
676 # Logic to handle issue #3664
676 # Logic to handle issue #3664
677 # Add '--' after '-m <module_name>' to ignore additional args passed to a module.
677 # Add '--' after '-m <module_name>' to ignore additional args passed to a module.
678 if '-m' in parameter_s and '--' not in parameter_s:
678 if '-m' in parameter_s and '--' not in parameter_s:
679 argv = shlex.split(parameter_s, posix=(os.name == 'posix'))
679 argv = shlex.split(parameter_s, posix=(os.name == 'posix'))
680 for idx, arg in enumerate(argv):
680 for idx, arg in enumerate(argv):
681 if arg and arg.startswith('-') and arg != '-':
681 if arg and arg.startswith('-') and arg != '-':
682 if arg == '-m':
682 if arg == '-m':
683 argv.insert(idx + 2, '--')
683 argv.insert(idx + 2, '--')
684 break
684 break
685 else:
685 else:
686 # Positional arg, break
686 # Positional arg, break
687 break
687 break
688 parameter_s = ' '.join(shlex.quote(arg) for arg in argv)
688 parameter_s = ' '.join(shlex.quote(arg) for arg in argv)
689
689
690 # get arguments and set sys.argv for program to be run.
690 # get arguments and set sys.argv for program to be run.
691 opts, arg_lst = self.parse_options(parameter_s,
691 opts, arg_lst = self.parse_options(parameter_s,
692 'nidtN:b:pD:l:rs:T:em:G',
692 'nidtN:b:pD:l:rs:T:em:G',
693 mode='list', list_all=1)
693 mode='list', list_all=1)
694 if "m" in opts:
694 if "m" in opts:
695 modulename = opts["m"][0]
695 modulename = opts["m"][0]
696 modpath = find_mod(modulename)
696 modpath = find_mod(modulename)
697 if modpath is None:
697 if modpath is None:
698 msg = '%r is not a valid modulename on sys.path'%modulename
698 msg = '%r is not a valid modulename on sys.path'%modulename
699 raise Exception(msg)
699 raise Exception(msg)
700 arg_lst = [modpath] + arg_lst
700 arg_lst = [modpath] + arg_lst
701 try:
701 try:
702 fpath = None # initialize to make sure fpath is in scope later
702 fpath = None # initialize to make sure fpath is in scope later
703 fpath = arg_lst[0]
703 fpath = arg_lst[0]
704 filename = file_finder(fpath)
704 filename = file_finder(fpath)
705 except IndexError as e:
705 except IndexError as e:
706 msg = 'you must provide at least a filename.'
706 msg = 'you must provide at least a filename.'
707 raise Exception(msg) from e
707 raise Exception(msg) from e
708 except IOError as e:
708 except IOError as e:
709 try:
709 try:
710 msg = str(e)
710 msg = str(e)
711 except UnicodeError:
711 except UnicodeError:
712 msg = e.message
712 msg = e.message
713 if os.name == 'nt' and re.match(r"^'.*'$",fpath):
713 if os.name == 'nt' and re.match(r"^'.*'$",fpath):
714 warn('For Windows, use double quotes to wrap a filename: %run "mypath\\myfile.py"')
714 warn('For Windows, use double quotes to wrap a filename: %run "mypath\\myfile.py"')
715 raise Exception(msg) from e
715 raise Exception(msg) from e
716 except TypeError:
716 except TypeError:
717 if fpath in sys.meta_path:
717 if fpath in sys.meta_path:
718 filename = ""
718 filename = ""
719 else:
719 else:
720 raise
720 raise
721
721
722 if filename.lower().endswith(('.ipy', '.ipynb')):
722 if filename.lower().endswith(('.ipy', '.ipynb')):
723 with preserve_keys(self.shell.user_ns, '__file__'):
723 with preserve_keys(self.shell.user_ns, '__file__'):
724 self.shell.user_ns['__file__'] = filename
724 self.shell.user_ns['__file__'] = filename
725 self.shell.safe_execfile_ipy(filename, raise_exceptions=True)
725 self.shell.safe_execfile_ipy(filename, raise_exceptions=True)
726 return
726 return
727
727
728 # Control the response to exit() calls made by the script being run
728 # Control the response to exit() calls made by the script being run
729 exit_ignore = 'e' in opts
729 exit_ignore = 'e' in opts
730
730
731 # Make sure that the running script gets a proper sys.argv as if it
731 # Make sure that the running script gets a proper sys.argv as if it
732 # were run from a system shell.
732 # were run from a system shell.
733 save_argv = sys.argv # save it for later restoring
733 save_argv = sys.argv # save it for later restoring
734
734
735 if 'G' in opts:
735 if 'G' in opts:
736 args = arg_lst[1:]
736 args = arg_lst[1:]
737 else:
737 else:
738 # tilde and glob expansion
738 # tilde and glob expansion
739 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
739 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
740
740
741 sys.argv = [filename] + args # put in the proper filename
741 sys.argv = [filename] + args # put in the proper filename
742
742
743 if 'n' in opts:
743 if 'n' in opts:
744 name = Path(filename).stem
744 name = Path(filename).stem
745 else:
745 else:
746 name = '__main__'
746 name = '__main__'
747
747
748 if 'i' in opts:
748 if 'i' in opts:
749 # Run in user's interactive namespace
749 # Run in user's interactive namespace
750 prog_ns = self.shell.user_ns
750 prog_ns = self.shell.user_ns
751 __name__save = self.shell.user_ns['__name__']
751 __name__save = self.shell.user_ns['__name__']
752 prog_ns['__name__'] = name
752 prog_ns['__name__'] = name
753 main_mod = self.shell.user_module
753 main_mod = self.shell.user_module
754
754
755 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
755 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
756 # set the __file__ global in the script's namespace
756 # set the __file__ global in the script's namespace
757 # TK: Is this necessary in interactive mode?
757 # TK: Is this necessary in interactive mode?
758 prog_ns['__file__'] = filename
758 prog_ns['__file__'] = filename
759 else:
759 else:
760 # Run in a fresh, empty namespace
760 # Run in a fresh, empty namespace
761
761
762 # The shell MUST hold a reference to prog_ns so after %run
762 # The shell MUST hold a reference to prog_ns so after %run
763 # exits, the python deletion mechanism doesn't zero it out
763 # exits, the python deletion mechanism doesn't zero it out
764 # (leaving dangling references). See interactiveshell for details
764 # (leaving dangling references). See interactiveshell for details
765 main_mod = self.shell.new_main_mod(filename, name)
765 main_mod = self.shell.new_main_mod(filename, name)
766 prog_ns = main_mod.__dict__
766 prog_ns = main_mod.__dict__
767
767
768 # pickle fix. See interactiveshell for an explanation. But we need to
768 # pickle fix. See interactiveshell for an explanation. But we need to
769 # make sure that, if we overwrite __main__, we replace it at the end
769 # make sure that, if we overwrite __main__, we replace it at the end
770 main_mod_name = prog_ns['__name__']
770 main_mod_name = prog_ns['__name__']
771
771
772 if main_mod_name == '__main__':
772 if main_mod_name == '__main__':
773 restore_main = sys.modules['__main__']
773 restore_main = sys.modules['__main__']
774 else:
774 else:
775 restore_main = False
775 restore_main = False
776
776
777 # This needs to be undone at the end to prevent holding references to
777 # This needs to be undone at the end to prevent holding references to
778 # every single object ever created.
778 # every single object ever created.
779 sys.modules[main_mod_name] = main_mod
779 sys.modules[main_mod_name] = main_mod
780
780
781 if 'p' in opts or 'd' in opts:
781 if 'p' in opts or 'd' in opts:
782 if 'm' in opts:
782 if 'm' in opts:
783 code = 'run_module(modulename, prog_ns)'
783 code = 'run_module(modulename, prog_ns)'
784 code_ns = {
784 code_ns = {
785 'run_module': self.shell.safe_run_module,
785 'run_module': self.shell.safe_run_module,
786 'prog_ns': prog_ns,
786 'prog_ns': prog_ns,
787 'modulename': modulename,
787 'modulename': modulename,
788 }
788 }
789 else:
789 else:
790 if 'd' in opts:
790 if 'd' in opts:
791 # allow exceptions to raise in debug mode
791 # allow exceptions to raise in debug mode
792 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
792 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
793 else:
793 else:
794 code = 'execfile(filename, prog_ns)'
794 code = 'execfile(filename, prog_ns)'
795 code_ns = {
795 code_ns = {
796 'execfile': self.shell.safe_execfile,
796 'execfile': self.shell.safe_execfile,
797 'prog_ns': prog_ns,
797 'prog_ns': prog_ns,
798 'filename': get_py_filename(filename),
798 'filename': get_py_filename(filename),
799 }
799 }
800
800
801 try:
801 try:
802 stats = None
802 stats = None
803 if 'p' in opts:
803 if 'p' in opts:
804 stats = self._run_with_profiler(code, opts, code_ns)
804 stats = self._run_with_profiler(code, opts, code_ns)
805 else:
805 else:
806 if 'd' in opts:
806 if 'd' in opts:
807 bp_file, bp_line = parse_breakpoint(
807 bp_file, bp_line = parse_breakpoint(
808 opts.get('b', ['1'])[0], filename)
808 opts.get('b', ['1'])[0], filename)
809 self._run_with_debugger(
809 self._run_with_debugger(
810 code, code_ns, filename, bp_line, bp_file)
810 code, code_ns, filename, bp_line, bp_file)
811 else:
811 else:
812 if 'm' in opts:
812 if 'm' in opts:
813 def run():
813 def run():
814 self.shell.safe_run_module(modulename, prog_ns)
814 self.shell.safe_run_module(modulename, prog_ns)
815 else:
815 else:
816 if runner is None:
816 if runner is None:
817 runner = self.default_runner
817 runner = self.default_runner
818 if runner is None:
818 if runner is None:
819 runner = self.shell.safe_execfile
819 runner = self.shell.safe_execfile
820
820
821 def run():
821 def run():
822 runner(filename, prog_ns, prog_ns,
822 runner(filename, prog_ns, prog_ns,
823 exit_ignore=exit_ignore)
823 exit_ignore=exit_ignore)
824
824
825 if 't' in opts:
825 if 't' in opts:
826 # timed execution
826 # timed execution
827 try:
827 try:
828 nruns = int(opts['N'][0])
828 nruns = int(opts['N'][0])
829 if nruns < 1:
829 if nruns < 1:
830 error('Number of runs must be >=1')
830 error('Number of runs must be >=1')
831 return
831 return
832 except (KeyError):
832 except (KeyError):
833 nruns = 1
833 nruns = 1
834 self._run_with_timing(run, nruns)
834 self._run_with_timing(run, nruns)
835 else:
835 else:
836 # regular execution
836 # regular execution
837 run()
837 run()
838
838
839 if 'i' in opts:
839 if 'i' in opts:
840 self.shell.user_ns['__name__'] = __name__save
840 self.shell.user_ns['__name__'] = __name__save
841 else:
841 else:
842 # update IPython interactive namespace
842 # update IPython interactive namespace
843
843
844 # Some forms of read errors on the file may mean the
844 # Some forms of read errors on the file may mean the
845 # __name__ key was never set; using pop we don't have to
845 # __name__ key was never set; using pop we don't have to
846 # worry about a possible KeyError.
846 # worry about a possible KeyError.
847 prog_ns.pop('__name__', None)
847 prog_ns.pop('__name__', None)
848
848
849 with preserve_keys(self.shell.user_ns, '__file__'):
849 with preserve_keys(self.shell.user_ns, '__file__'):
850 self.shell.user_ns.update(prog_ns)
850 self.shell.user_ns.update(prog_ns)
851 finally:
851 finally:
852 # It's a bit of a mystery why, but __builtins__ can change from
852 # It's a bit of a mystery why, but __builtins__ can change from
853 # being a module to becoming a dict missing some key data after
853 # being a module to becoming a dict missing some key data after
854 # %run. As best I can see, this is NOT something IPython is doing
854 # %run. As best I can see, this is NOT something IPython is doing
855 # at all, and similar problems have been reported before:
855 # at all, and similar problems have been reported before:
856 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
856 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
857 # Since this seems to be done by the interpreter itself, the best
857 # Since this seems to be done by the interpreter itself, the best
858 # we can do is to at least restore __builtins__ for the user on
858 # we can do is to at least restore __builtins__ for the user on
859 # exit.
859 # exit.
860 self.shell.user_ns['__builtins__'] = builtin_mod
860 self.shell.user_ns['__builtins__'] = builtin_mod
861
861
862 # Ensure key global structures are restored
862 # Ensure key global structures are restored
863 sys.argv = save_argv
863 sys.argv = save_argv
864 if restore_main:
864 if restore_main:
865 sys.modules['__main__'] = restore_main
865 sys.modules['__main__'] = restore_main
866 if '__mp_main__' in sys.modules:
866 if '__mp_main__' in sys.modules:
867 sys.modules['__mp_main__'] = restore_main
867 sys.modules['__mp_main__'] = restore_main
868 else:
868 else:
869 # Remove from sys.modules the reference to main_mod we'd
869 # Remove from sys.modules the reference to main_mod we'd
870 # added. Otherwise it will trap references to objects
870 # added. Otherwise it will trap references to objects
871 # contained therein.
871 # contained therein.
872 del sys.modules[main_mod_name]
872 del sys.modules[main_mod_name]
873
873
874 return stats
874 return stats
875
875
876 def _run_with_debugger(self, code, code_ns, filename=None,
876 def _run_with_debugger(self, code, code_ns, filename=None,
877 bp_line=None, bp_file=None):
877 bp_line=None, bp_file=None):
878 """
878 """
879 Run `code` in debugger with a break point.
879 Run `code` in debugger with a break point.
880
880
881 Parameters
881 Parameters
882 ----------
882 ----------
883 code : str
883 code : str
884 Code to execute.
884 Code to execute.
885 code_ns : dict
885 code_ns : dict
886 A namespace in which `code` is executed.
886 A namespace in which `code` is executed.
887 filename : str
887 filename : str
888 `code` is ran as if it is in `filename`.
888 `code` is ran as if it is in `filename`.
889 bp_line : int, optional
889 bp_line : int, optional
890 Line number of the break point.
890 Line number of the break point.
891 bp_file : str, optional
891 bp_file : str, optional
892 Path to the file in which break point is specified.
892 Path to the file in which break point is specified.
893 `filename` is used if not given.
893 `filename` is used if not given.
894
894
895 Raises
895 Raises
896 ------
896 ------
897 UsageError
897 UsageError
898 If the break point given by `bp_line` is not valid.
898 If the break point given by `bp_line` is not valid.
899
899
900 """
900 """
901 deb = self.shell.InteractiveTB.pdb
901 deb = self.shell.InteractiveTB.pdb
902 if not deb:
902 if not deb:
903 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
903 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
904 deb = self.shell.InteractiveTB.pdb
904 deb = self.shell.InteractiveTB.pdb
905
905
906 # deb.checkline() fails if deb.curframe exists but is None; it can
906 # deb.checkline() fails if deb.curframe exists but is None; it can
907 # handle it not existing. https://github.com/ipython/ipython/issues/10028
907 # handle it not existing. https://github.com/ipython/ipython/issues/10028
908 if hasattr(deb, 'curframe'):
908 if hasattr(deb, 'curframe'):
909 del deb.curframe
909 del deb.curframe
910
910
911 # reset Breakpoint state, which is moronically kept
911 # reset Breakpoint state, which is moronically kept
912 # in a class
912 # in a class
913 bdb.Breakpoint.next = 1
913 bdb.Breakpoint.next = 1
914 bdb.Breakpoint.bplist = {}
914 bdb.Breakpoint.bplist = {}
915 bdb.Breakpoint.bpbynumber = [None]
915 bdb.Breakpoint.bpbynumber = [None]
916 deb.clear_all_breaks()
916 deb.clear_all_breaks()
917 if bp_line is not None:
917 if bp_line is not None:
918 # Set an initial breakpoint to stop execution
918 # Set an initial breakpoint to stop execution
919 maxtries = 10
919 maxtries = 10
920 bp_file = bp_file or filename
920 bp_file = bp_file or filename
921 checkline = deb.checkline(bp_file, bp_line)
921 checkline = deb.checkline(bp_file, bp_line)
922 if not checkline:
922 if not checkline:
923 for bp in range(bp_line + 1, bp_line + maxtries + 1):
923 for bp in range(bp_line + 1, bp_line + maxtries + 1):
924 if deb.checkline(bp_file, bp):
924 if deb.checkline(bp_file, bp):
925 break
925 break
926 else:
926 else:
927 msg = ("\nI failed to find a valid line to set "
927 msg = ("\nI failed to find a valid line to set "
928 "a breakpoint\n"
928 "a breakpoint\n"
929 "after trying up to line: %s.\n"
929 "after trying up to line: %s.\n"
930 "Please set a valid breakpoint manually "
930 "Please set a valid breakpoint manually "
931 "with the -b option." % bp)
931 "with the -b option." % bp)
932 raise UsageError(msg)
932 raise UsageError(msg)
933 # if we find a good linenumber, set the breakpoint
933 # if we find a good linenumber, set the breakpoint
934 deb.do_break('%s:%s' % (bp_file, bp_line))
934 deb.do_break('%s:%s' % (bp_file, bp_line))
935
935
936 if filename:
936 if filename:
937 # Mimic Pdb._runscript(...)
937 # Mimic Pdb._runscript(...)
938 deb._wait_for_mainpyfile = True
938 deb._wait_for_mainpyfile = True
939 deb.mainpyfile = deb.canonic(filename)
939 deb.mainpyfile = deb.canonic(filename)
940
940
941 # Start file run
941 # Start file run
942 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
942 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
943 try:
943 try:
944 if filename:
944 if filename:
945 # save filename so it can be used by methods on the deb object
945 # save filename so it can be used by methods on the deb object
946 deb._exec_filename = filename
946 deb._exec_filename = filename
947 while True:
947 while True:
948 try:
948 try:
949 trace = sys.gettrace()
949 trace = sys.gettrace()
950 deb.run(code, code_ns)
950 deb.run(code, code_ns)
951 except Restart:
951 except Restart:
952 print("Restarting")
952 print("Restarting")
953 if filename:
953 if filename:
954 deb._wait_for_mainpyfile = True
954 deb._wait_for_mainpyfile = True
955 deb.mainpyfile = deb.canonic(filename)
955 deb.mainpyfile = deb.canonic(filename)
956 continue
956 continue
957 else:
957 else:
958 break
958 break
959 finally:
959 finally:
960 sys.settrace(trace)
960 sys.settrace(trace)
961
961
962
962
963 except:
963 except:
964 etype, value, tb = sys.exc_info()
964 etype, value, tb = sys.exc_info()
965 # Skip three frames in the traceback: the %run one,
965 # Skip three frames in the traceback: the %run one,
966 # one inside bdb.py, and the command-line typed by the
966 # one inside bdb.py, and the command-line typed by the
967 # user (run by exec in pdb itself).
967 # user (run by exec in pdb itself).
968 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
968 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
969
969
970 @staticmethod
970 @staticmethod
971 def _run_with_timing(run, nruns):
971 def _run_with_timing(run, nruns):
972 """
972 """
973 Run function `run` and print timing information.
973 Run function `run` and print timing information.
974
974
975 Parameters
975 Parameters
976 ----------
976 ----------
977 run : callable
977 run : callable
978 Any callable object which takes no argument.
978 Any callable object which takes no argument.
979 nruns : int
979 nruns : int
980 Number of times to execute `run`.
980 Number of times to execute `run`.
981
981
982 """
982 """
983 twall0 = time.perf_counter()
983 twall0 = time.perf_counter()
984 if nruns == 1:
984 if nruns == 1:
985 t0 = clock2()
985 t0 = clock2()
986 run()
986 run()
987 t1 = clock2()
987 t1 = clock2()
988 t_usr = t1[0] - t0[0]
988 t_usr = t1[0] - t0[0]
989 t_sys = t1[1] - t0[1]
989 t_sys = t1[1] - t0[1]
990 print("\nIPython CPU timings (estimated):")
990 print("\nIPython CPU timings (estimated):")
991 print(" User : %10.2f s." % t_usr)
991 print(" User : %10.2f s." % t_usr)
992 print(" System : %10.2f s." % t_sys)
992 print(" System : %10.2f s." % t_sys)
993 else:
993 else:
994 runs = range(nruns)
994 runs = range(nruns)
995 t0 = clock2()
995 t0 = clock2()
996 for nr in runs:
996 for nr in runs:
997 run()
997 run()
998 t1 = clock2()
998 t1 = clock2()
999 t_usr = t1[0] - t0[0]
999 t_usr = t1[0] - t0[0]
1000 t_sys = t1[1] - t0[1]
1000 t_sys = t1[1] - t0[1]
1001 print("\nIPython CPU timings (estimated):")
1001 print("\nIPython CPU timings (estimated):")
1002 print("Total runs performed:", nruns)
1002 print("Total runs performed:", nruns)
1003 print(" Times : %10s %10s" % ('Total', 'Per run'))
1003 print(" Times : %10s %10s" % ('Total', 'Per run'))
1004 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
1004 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
1005 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
1005 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
1006 twall1 = time.perf_counter()
1006 twall1 = time.perf_counter()
1007 print("Wall time: %10.2f s." % (twall1 - twall0))
1007 print("Wall time: %10.2f s." % (twall1 - twall0))
1008
1008
1009 @skip_doctest
1009 @skip_doctest
1010 @no_var_expand
1010 @no_var_expand
1011 @line_cell_magic
1011 @line_cell_magic
1012 @needs_local_scope
1012 @needs_local_scope
1013 def timeit(self, line='', cell=None, local_ns=None):
1013 def timeit(self, line='', cell=None, local_ns=None):
1014 """Time execution of a Python statement or expression
1014 """Time execution of a Python statement or expression
1015
1015
1016 Usage, in line mode:
1016 Usage, in line mode:
1017 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
1017 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
1018 or in cell mode:
1018 or in cell mode:
1019 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
1019 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
1020 code
1020 code
1021 code...
1021 code...
1022
1022
1023 Time execution of a Python statement or expression using the timeit
1023 Time execution of a Python statement or expression using the timeit
1024 module. This function can be used both as a line and cell magic:
1024 module. This function can be used both as a line and cell magic:
1025
1025
1026 - In line mode you can time a single-line statement (though multiple
1026 - In line mode you can time a single-line statement (though multiple
1027 ones can be chained with using semicolons).
1027 ones can be chained with using semicolons).
1028
1028
1029 - In cell mode, the statement in the first line is used as setup code
1029 - In cell mode, the statement in the first line is used as setup code
1030 (executed but not timed) and the body of the cell is timed. The cell
1030 (executed but not timed) and the body of the cell is timed. The cell
1031 body has access to any variables created in the setup code.
1031 body has access to any variables created in the setup code.
1032
1032
1033 Options:
1033 Options:
1034 -n<N>: execute the given statement <N> times in a loop. If <N> is not
1034 -n<N>: execute the given statement <N> times in a loop. If <N> is not
1035 provided, <N> is determined so as to get sufficient accuracy.
1035 provided, <N> is determined so as to get sufficient accuracy.
1036
1036
1037 -r<R>: number of repeats <R>, each consisting of <N> loops, and take the
1037 -r<R>: number of repeats <R>, each consisting of <N> loops, and take the
1038 best result.
1038 best result.
1039 Default: 7
1039 Default: 7
1040
1040
1041 -t: use time.time to measure the time, which is the default on Unix.
1041 -t: use time.time to measure the time, which is the default on Unix.
1042 This function measures wall time.
1042 This function measures wall time.
1043
1043
1044 -c: use time.clock to measure the time, which is the default on
1044 -c: use time.clock to measure the time, which is the default on
1045 Windows and measures wall time. On Unix, resource.getrusage is used
1045 Windows and measures wall time. On Unix, resource.getrusage is used
1046 instead and returns the CPU user time.
1046 instead and returns the CPU user time.
1047
1047
1048 -p<P>: use a precision of <P> digits to display the timing result.
1048 -p<P>: use a precision of <P> digits to display the timing result.
1049 Default: 3
1049 Default: 3
1050
1050
1051 -q: Quiet, do not print result.
1051 -q: Quiet, do not print result.
1052
1052
1053 -o: return a TimeitResult that can be stored in a variable to inspect
1053 -o: return a TimeitResult that can be stored in a variable to inspect
1054 the result in more details.
1054 the result in more details.
1055
1055
1056 .. versionchanged:: 7.3
1056 .. versionchanged:: 7.3
1057 User variables are no longer expanded,
1057 User variables are no longer expanded,
1058 the magic line is always left unmodified.
1058 the magic line is always left unmodified.
1059
1059
1060 Examples
1060 Examples
1061 --------
1061 --------
1062 ::
1062 ::
1063
1063
1064 In [1]: %timeit pass
1064 In [1]: %timeit pass
1065 8.26 ns ± 0.12 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
1065 8.26 ns ± 0.12 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
1066
1066
1067 In [2]: u = None
1067 In [2]: u = None
1068
1068
1069 In [3]: %timeit u is None
1069 In [3]: %timeit u is None
1070 29.9 ns ± 0.643 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
1070 29.9 ns ± 0.643 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
1071
1071
1072 In [4]: %timeit -r 4 u == None
1072 In [4]: %timeit -r 4 u == None
1073
1073
1074 In [5]: import time
1074 In [5]: import time
1075
1075
1076 In [6]: %timeit -n1 time.sleep(2)
1076 In [6]: %timeit -n1 time.sleep(2)
1077
1077
1078
1078
1079 The times reported by %timeit will be slightly higher than those
1079 The times reported by %timeit will be slightly higher than those
1080 reported by the timeit.py script when variables are accessed. This is
1080 reported by the timeit.py script when variables are accessed. This is
1081 due to the fact that %timeit executes the statement in the namespace
1081 due to the fact that %timeit executes the statement in the namespace
1082 of the shell, compared with timeit.py, which uses a single setup
1082 of the shell, compared with timeit.py, which uses a single setup
1083 statement to import function or create variables. Generally, the bias
1083 statement to import function or create variables. Generally, the bias
1084 does not matter as long as results from timeit.py are not mixed with
1084 does not matter as long as results from timeit.py are not mixed with
1085 those from %timeit."""
1085 those from %timeit."""
1086
1086
1087 opts, stmt = self.parse_options(
1087 opts, stmt = self.parse_options(
1088 line, "n:r:tcp:qo", posix=False, strict=False, preserve_non_opts=True
1088 line, "n:r:tcp:qo", posix=False, strict=False, preserve_non_opts=True
1089 )
1089 )
1090 if stmt == "" and cell is None:
1090 if stmt == "" and cell is None:
1091 return
1091 return
1092
1092
1093 timefunc = timeit.default_timer
1093 timefunc = timeit.default_timer
1094 number = int(getattr(opts, "n", 0))
1094 number = int(getattr(opts, "n", 0))
1095 default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat
1095 default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat
1096 repeat = int(getattr(opts, "r", default_repeat))
1096 repeat = int(getattr(opts, "r", default_repeat))
1097 precision = int(getattr(opts, "p", 3))
1097 precision = int(getattr(opts, "p", 3))
1098 quiet = 'q' in opts
1098 quiet = 'q' in opts
1099 return_result = 'o' in opts
1099 return_result = 'o' in opts
1100 if hasattr(opts, "t"):
1100 if hasattr(opts, "t"):
1101 timefunc = time.time
1101 timefunc = time.time
1102 if hasattr(opts, "c"):
1102 if hasattr(opts, "c"):
1103 timefunc = clock
1103 timefunc = clock
1104
1104
1105 timer = Timer(timer=timefunc)
1105 timer = Timer(timer=timefunc)
1106 # this code has tight coupling to the inner workings of timeit.Timer,
1106 # this code has tight coupling to the inner workings of timeit.Timer,
1107 # but is there a better way to achieve that the code stmt has access
1107 # but is there a better way to achieve that the code stmt has access
1108 # to the shell namespace?
1108 # to the shell namespace?
1109 transform = self.shell.transform_cell
1109 transform = self.shell.transform_cell
1110
1110
1111 if cell is None:
1111 if cell is None:
1112 # called as line magic
1112 # called as line magic
1113 ast_setup = self.shell.compile.ast_parse("pass")
1113 ast_setup = self.shell.compile.ast_parse("pass")
1114 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1114 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1115 else:
1115 else:
1116 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1116 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1117 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1117 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1118
1118
1119 ast_setup = self.shell.transform_ast(ast_setup)
1119 ast_setup = self.shell.transform_ast(ast_setup)
1120 ast_stmt = self.shell.transform_ast(ast_stmt)
1120 ast_stmt = self.shell.transform_ast(ast_stmt)
1121
1121
1122 # Check that these compile to valid Python code *outside* the timer func
1122 # Check that these compile to valid Python code *outside* the timer func
1123 # Invalid code may become valid when put inside the function & loop,
1123 # Invalid code may become valid when put inside the function & loop,
1124 # which messes up error messages.
1124 # which messes up error messages.
1125 # https://github.com/ipython/ipython/issues/10636
1125 # https://github.com/ipython/ipython/issues/10636
1126 self.shell.compile(ast_setup, "<magic-timeit-setup>", "exec")
1126 self.shell.compile(ast_setup, "<magic-timeit-setup>", "exec")
1127 self.shell.compile(ast_stmt, "<magic-timeit-stmt>", "exec")
1127 self.shell.compile(ast_stmt, "<magic-timeit-stmt>", "exec")
1128
1128
1129 # This codestring is taken from timeit.template - we fill it in as an
1129 # This codestring is taken from timeit.template - we fill it in as an
1130 # AST, so that we can apply our AST transformations to the user code
1130 # AST, so that we can apply our AST transformations to the user code
1131 # without affecting the timing code.
1131 # without affecting the timing code.
1132 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1132 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1133 ' setup\n'
1133 ' setup\n'
1134 ' _t0 = _timer()\n'
1134 ' _t0 = _timer()\n'
1135 ' for _i in _it:\n'
1135 ' for _i in _it:\n'
1136 ' stmt\n'
1136 ' stmt\n'
1137 ' _t1 = _timer()\n'
1137 ' _t1 = _timer()\n'
1138 ' return _t1 - _t0\n')
1138 ' return _t1 - _t0\n')
1139
1139
1140 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1140 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1141 timeit_ast = ast.fix_missing_locations(timeit_ast)
1141 timeit_ast = ast.fix_missing_locations(timeit_ast)
1142
1142
1143 # Track compilation time so it can be reported if too long
1143 # Track compilation time so it can be reported if too long
1144 # Minimum time above which compilation time will be reported
1144 # Minimum time above which compilation time will be reported
1145 tc_min = 0.1
1145 tc_min = 0.1
1146
1146
1147 t0 = clock()
1147 t0 = clock()
1148 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1148 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1149 tc = clock()-t0
1149 tc = clock()-t0
1150
1150
1151 ns = {}
1151 ns = {}
1152 glob = self.shell.user_ns
1152 glob = self.shell.user_ns
1153 # handles global vars with same name as local vars. We store them in conflict_globs.
1153 # handles global vars with same name as local vars. We store them in conflict_globs.
1154 conflict_globs = {}
1154 conflict_globs = {}
1155 if local_ns and cell is None:
1155 if local_ns and cell is None:
1156 for var_name, var_val in glob.items():
1156 for var_name, var_val in glob.items():
1157 if var_name in local_ns:
1157 if var_name in local_ns:
1158 conflict_globs[var_name] = var_val
1158 conflict_globs[var_name] = var_val
1159 glob.update(local_ns)
1159 glob.update(local_ns)
1160
1160
1161 exec(code, glob, ns)
1161 exec(code, glob, ns)
1162 timer.inner = ns["inner"]
1162 timer.inner = ns["inner"]
1163
1163
1164 # This is used to check if there is a huge difference between the
1164 # This is used to check if there is a huge difference between the
1165 # best and worst timings.
1165 # best and worst timings.
1166 # Issue: https://github.com/ipython/ipython/issues/6471
1166 # Issue: https://github.com/ipython/ipython/issues/6471
1167 if number == 0:
1167 if number == 0:
1168 # determine number so that 0.2 <= total time < 2.0
1168 # determine number so that 0.2 <= total time < 2.0
1169 for index in range(0, 10):
1169 for index in range(0, 10):
1170 number = 10 ** index
1170 number = 10 ** index
1171 time_number = timer.timeit(number)
1171 time_number = timer.timeit(number)
1172 if time_number >= 0.2:
1172 if time_number >= 0.2:
1173 break
1173 break
1174
1174
1175 all_runs = timer.repeat(repeat, number)
1175 all_runs = timer.repeat(repeat, number)
1176 best = min(all_runs) / number
1176 best = min(all_runs) / number
1177 worst = max(all_runs) / number
1177 worst = max(all_runs) / number
1178 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1178 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1179
1179
1180 # Restore global vars from conflict_globs
1180 # Restore global vars from conflict_globs
1181 if conflict_globs:
1181 if conflict_globs:
1182 glob.update(conflict_globs)
1182 glob.update(conflict_globs)
1183
1183
1184 if not quiet :
1184 if not quiet :
1185 # Check best timing is greater than zero to avoid a
1185 # Check best timing is greater than zero to avoid a
1186 # ZeroDivisionError.
1186 # ZeroDivisionError.
1187 # In cases where the slowest timing is lesser than a microsecond
1187 # In cases where the slowest timing is lesser than a microsecond
1188 # we assume that it does not really matter if the fastest
1188 # we assume that it does not really matter if the fastest
1189 # timing is 4 times faster than the slowest timing or not.
1189 # timing is 4 times faster than the slowest timing or not.
1190 if worst > 4 * best and best > 0 and worst > 1e-6:
1190 if worst > 4 * best and best > 0 and worst > 1e-6:
1191 print("The slowest run took %0.2f times longer than the "
1191 print("The slowest run took %0.2f times longer than the "
1192 "fastest. This could mean that an intermediate result "
1192 "fastest. This could mean that an intermediate result "
1193 "is being cached." % (worst / best))
1193 "is being cached." % (worst / best))
1194
1194
1195 print( timeit_result )
1195 print( timeit_result )
1196
1196
1197 if tc > tc_min:
1197 if tc > tc_min:
1198 print("Compiler time: %.2f s" % tc)
1198 print("Compiler time: %.2f s" % tc)
1199 if return_result:
1199 if return_result:
1200 return timeit_result
1200 return timeit_result
1201
1201
1202 @skip_doctest
1202 @skip_doctest
1203 @no_var_expand
1203 @no_var_expand
1204 @needs_local_scope
1204 @needs_local_scope
1205 @line_cell_magic
1205 @line_cell_magic
1206 def time(self,line='', cell=None, local_ns=None):
1206 def time(self,line='', cell=None, local_ns=None):
1207 """Time execution of a Python statement or expression.
1207 """Time execution of a Python statement or expression.
1208
1208
1209 The CPU and wall clock times are printed, and the value of the
1209 The CPU and wall clock times are printed, and the value of the
1210 expression (if any) is returned. Note that under Win32, system time
1210 expression (if any) is returned. Note that under Win32, system time
1211 is always reported as 0, since it can not be measured.
1211 is always reported as 0, since it can not be measured.
1212
1212
1213 This function can be used both as a line and cell magic:
1213 This function can be used both as a line and cell magic:
1214
1214
1215 - In line mode you can time a single-line statement (though multiple
1215 - In line mode you can time a single-line statement (though multiple
1216 ones can be chained with using semicolons).
1216 ones can be chained with using semicolons).
1217
1217
1218 - In cell mode, you can time the cell body (a directly
1218 - In cell mode, you can time the cell body (a directly
1219 following statement raises an error).
1219 following statement raises an error).
1220
1220
1221 This function provides very basic timing functionality. Use the timeit
1221 This function provides very basic timing functionality. Use the timeit
1222 magic for more control over the measurement.
1222 magic for more control over the measurement.
1223
1223
1224 .. versionchanged:: 7.3
1224 .. versionchanged:: 7.3
1225 User variables are no longer expanded,
1225 User variables are no longer expanded,
1226 the magic line is always left unmodified.
1226 the magic line is always left unmodified.
1227
1227
1228 Examples
1228 Examples
1229 --------
1229 --------
1230 ::
1230 ::
1231
1231
1232 In [1]: %time 2**128
1232 In [1]: %time 2**128
1233 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1233 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1234 Wall time: 0.00
1234 Wall time: 0.00
1235 Out[1]: 340282366920938463463374607431768211456L
1235 Out[1]: 340282366920938463463374607431768211456L
1236
1236
1237 In [2]: n = 1000000
1237 In [2]: n = 1000000
1238
1238
1239 In [3]: %time sum(range(n))
1239 In [3]: %time sum(range(n))
1240 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1240 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1241 Wall time: 1.37
1241 Wall time: 1.37
1242 Out[3]: 499999500000L
1242 Out[3]: 499999500000L
1243
1243
1244 In [4]: %time print 'hello world'
1244 In [4]: %time print 'hello world'
1245 hello world
1245 hello world
1246 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1246 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1247 Wall time: 0.00
1247 Wall time: 0.00
1248
1248
1249
1249
1250 .. note::
1250 .. note::
1251 The time needed by Python to compile the given expression will be
1251 The time needed by Python to compile the given expression will be
1252 reported if it is more than 0.1s.
1252 reported if it is more than 0.1s.
1253
1253
1254 In the example below, the actual exponentiation is done by Python
1254 In the example below, the actual exponentiation is done by Python
1255 at compilation time, so while the expression can take a noticeable
1255 at compilation time, so while the expression can take a noticeable
1256 amount of time to compute, that time is purely due to the
1256 amount of time to compute, that time is purely due to the
1257 compilation::
1257 compilation::
1258
1258
1259 In [5]: %time 3**9999;
1259 In [5]: %time 3**9999;
1260 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1260 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1261 Wall time: 0.00 s
1261 Wall time: 0.00 s
1262
1262
1263 In [6]: %time 3**999999;
1263 In [6]: %time 3**999999;
1264 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1264 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1265 Wall time: 0.00 s
1265 Wall time: 0.00 s
1266 Compiler : 0.78 s
1266 Compiler : 0.78 s
1267 """
1267 """
1268 # fail immediately if the given expression can't be compiled
1268 # fail immediately if the given expression can't be compiled
1269
1269
1270 if line and cell:
1270 if line and cell:
1271 raise UsageError("Can't use statement directly after '%%time'!")
1271 raise UsageError("Can't use statement directly after '%%time'!")
1272
1272
1273 if cell:
1273 if cell:
1274 expr = self.shell.transform_cell(cell)
1274 expr = self.shell.transform_cell(cell)
1275 else:
1275 else:
1276 expr = self.shell.transform_cell(line)
1276 expr = self.shell.transform_cell(line)
1277
1277
1278 # Minimum time above which parse time will be reported
1278 # Minimum time above which parse time will be reported
1279 tp_min = 0.1
1279 tp_min = 0.1
1280
1280
1281 t0 = clock()
1281 t0 = clock()
1282 expr_ast = self.shell.compile.ast_parse(expr)
1282 expr_ast = self.shell.compile.ast_parse(expr)
1283 tp = clock()-t0
1283 tp = clock()-t0
1284
1284
1285 # Apply AST transformations
1285 # Apply AST transformations
1286 expr_ast = self.shell.transform_ast(expr_ast)
1286 expr_ast = self.shell.transform_ast(expr_ast)
1287
1287
1288 # Minimum time above which compilation time will be reported
1288 # Minimum time above which compilation time will be reported
1289 tc_min = 0.1
1289 tc_min = 0.1
1290
1290
1291 expr_val=None
1291 expr_val=None
1292 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1292 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1293 mode = 'eval'
1293 mode = 'eval'
1294 source = '<timed eval>'
1294 source = '<timed eval>'
1295 expr_ast = ast.Expression(expr_ast.body[0].value)
1295 expr_ast = ast.Expression(expr_ast.body[0].value)
1296 else:
1296 else:
1297 mode = 'exec'
1297 mode = 'exec'
1298 source = '<timed exec>'
1298 source = '<timed exec>'
1299 # multi-line %%time case
1299 # multi-line %%time case
1300 if len(expr_ast.body) > 1 and isinstance(expr_ast.body[-1], ast.Expr):
1300 if len(expr_ast.body) > 1 and isinstance(expr_ast.body[-1], ast.Expr):
1301 expr_val= expr_ast.body[-1]
1301 expr_val= expr_ast.body[-1]
1302 expr_ast = expr_ast.body[:-1]
1302 expr_ast = expr_ast.body[:-1]
1303 expr_ast = Module(expr_ast, [])
1303 expr_ast = Module(expr_ast, [])
1304 expr_val = ast.Expression(expr_val.value)
1304 expr_val = ast.Expression(expr_val.value)
1305
1305
1306 t0 = clock()
1306 t0 = clock()
1307 code = self.shell.compile(expr_ast, source, mode)
1307 code = self.shell.compile(expr_ast, source, mode)
1308 tc = clock()-t0
1308 tc = clock()-t0
1309
1309
1310 # skew measurement as little as possible
1310 # skew measurement as little as possible
1311 glob = self.shell.user_ns
1311 glob = self.shell.user_ns
1312 wtime = time.time
1312 wtime = time.time
1313 # time execution
1313 # time execution
1314 wall_st = wtime()
1314 wall_st = wtime()
1315 if mode=='eval':
1315 if mode=='eval':
1316 st = clock2()
1316 st = clock2()
1317 try:
1317 try:
1318 out = eval(code, glob, local_ns)
1318 out = eval(code, glob, local_ns)
1319 except:
1319 except:
1320 self.shell.showtraceback()
1320 self.shell.showtraceback()
1321 return
1321 return
1322 end = clock2()
1322 end = clock2()
1323 else:
1323 else:
1324 st = clock2()
1324 st = clock2()
1325 try:
1325 try:
1326 exec(code, glob, local_ns)
1326 exec(code, glob, local_ns)
1327 out=None
1327 out=None
1328 # multi-line %%time case
1328 # multi-line %%time case
1329 if expr_val is not None:
1329 if expr_val is not None:
1330 code_2 = self.shell.compile(expr_val, source, 'eval')
1330 code_2 = self.shell.compile(expr_val, source, 'eval')
1331 out = eval(code_2, glob, local_ns)
1331 out = eval(code_2, glob, local_ns)
1332 except:
1332 except:
1333 self.shell.showtraceback()
1333 self.shell.showtraceback()
1334 return
1334 return
1335 end = clock2()
1335 end = clock2()
1336
1336
1337 wall_end = wtime()
1337 wall_end = wtime()
1338 # Compute actual times and report
1338 # Compute actual times and report
1339 wall_time = wall_end-wall_st
1339 wall_time = wall_end-wall_st
1340 cpu_user = end[0]-st[0]
1340 cpu_user = end[0]-st[0]
1341 cpu_sys = end[1]-st[1]
1341 cpu_sys = end[1]-st[1]
1342 cpu_tot = cpu_user+cpu_sys
1342 cpu_tot = cpu_user+cpu_sys
1343 # On windows cpu_sys is always zero, so no new information to the next print
1343 # On windows cpu_sys is always zero, so no new information to the next print
1344 if sys.platform != 'win32':
1344 if sys.platform != 'win32':
1345 print("CPU times: user %s, sys: %s, total: %s" % \
1345 print("CPU times: user %s, sys: %s, total: %s" % \
1346 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1346 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1347 print("Wall time: %s" % _format_time(wall_time))
1347 print("Wall time: %s" % _format_time(wall_time))
1348 if tc > tc_min:
1348 if tc > tc_min:
1349 print("Compiler : %s" % _format_time(tc))
1349 print("Compiler : %s" % _format_time(tc))
1350 if tp > tp_min:
1350 if tp > tp_min:
1351 print("Parser : %s" % _format_time(tp))
1351 print("Parser : %s" % _format_time(tp))
1352 return out
1352 return out
1353
1353
1354 @skip_doctest
1354 @skip_doctest
1355 @line_magic
1355 @line_magic
1356 def macro(self, parameter_s=''):
1356 def macro(self, parameter_s=''):
1357 """Define a macro for future re-execution. It accepts ranges of history,
1357 """Define a macro for future re-execution. It accepts ranges of history,
1358 filenames or string objects.
1358 filenames or string objects.
1359
1359
1360 Usage:\\
1360 Usage:\\
1361 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1361 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1362
1362
1363 Options:
1363 Options:
1364
1364
1365 -r: use 'raw' input. By default, the 'processed' history is used,
1365 -r: use 'raw' input. By default, the 'processed' history is used,
1366 so that magics are loaded in their transformed version to valid
1366 so that magics are loaded in their transformed version to valid
1367 Python. If this option is given, the raw input as typed at the
1367 Python. If this option is given, the raw input as typed at the
1368 command line is used instead.
1368 command line is used instead.
1369
1369
1370 -q: quiet macro definition. By default, a tag line is printed
1370 -q: quiet macro definition. By default, a tag line is printed
1371 to indicate the macro has been created, and then the contents of
1371 to indicate the macro has been created, and then the contents of
1372 the macro are printed. If this option is given, then no printout
1372 the macro are printed. If this option is given, then no printout
1373 is produced once the macro is created.
1373 is produced once the macro is created.
1374
1374
1375 This will define a global variable called `name` which is a string
1375 This will define a global variable called `name` which is a string
1376 made of joining the slices and lines you specify (n1,n2,... numbers
1376 made of joining the slices and lines you specify (n1,n2,... numbers
1377 above) from your input history into a single string. This variable
1377 above) from your input history into a single string. This variable
1378 acts like an automatic function which re-executes those lines as if
1378 acts like an automatic function which re-executes those lines as if
1379 you had typed them. You just type 'name' at the prompt and the code
1379 you had typed them. You just type 'name' at the prompt and the code
1380 executes.
1380 executes.
1381
1381
1382 The syntax for indicating input ranges is described in %history.
1382 The syntax for indicating input ranges is described in %history.
1383
1383
1384 Note: as a 'hidden' feature, you can also use traditional python slice
1384 Note: as a 'hidden' feature, you can also use traditional python slice
1385 notation, where N:M means numbers N through M-1.
1385 notation, where N:M means numbers N through M-1.
1386
1386
1387 For example, if your history contains (print using %hist -n )::
1387 For example, if your history contains (print using %hist -n )::
1388
1388
1389 44: x=1
1389 44: x=1
1390 45: y=3
1390 45: y=3
1391 46: z=x+y
1391 46: z=x+y
1392 47: print x
1392 47: print x
1393 48: a=5
1393 48: a=5
1394 49: print 'x',x,'y',y
1394 49: print 'x',x,'y',y
1395
1395
1396 you can create a macro with lines 44 through 47 (included) and line 49
1396 you can create a macro with lines 44 through 47 (included) and line 49
1397 called my_macro with::
1397 called my_macro with::
1398
1398
1399 In [55]: %macro my_macro 44-47 49
1399 In [55]: %macro my_macro 44-47 49
1400
1400
1401 Now, typing `my_macro` (without quotes) will re-execute all this code
1401 Now, typing `my_macro` (without quotes) will re-execute all this code
1402 in one pass.
1402 in one pass.
1403
1403
1404 You don't need to give the line-numbers in order, and any given line
1404 You don't need to give the line-numbers in order, and any given line
1405 number can appear multiple times. You can assemble macros with any
1405 number can appear multiple times. You can assemble macros with any
1406 lines from your input history in any order.
1406 lines from your input history in any order.
1407
1407
1408 The macro is a simple object which holds its value in an attribute,
1408 The macro is a simple object which holds its value in an attribute,
1409 but IPython's display system checks for macros and executes them as
1409 but IPython's display system checks for macros and executes them as
1410 code instead of printing them when you type their name.
1410 code instead of printing them when you type their name.
1411
1411
1412 You can view a macro's contents by explicitly printing it with::
1412 You can view a macro's contents by explicitly printing it with::
1413
1413
1414 print macro_name
1414 print macro_name
1415
1415
1416 """
1416 """
1417 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1417 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1418 if not args: # List existing macros
1418 if not args: # List existing macros
1419 return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro))
1419 return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro))
1420 if len(args) == 1:
1420 if len(args) == 1:
1421 raise UsageError(
1421 raise UsageError(
1422 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1422 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1423 name, codefrom = args[0], " ".join(args[1:])
1423 name, codefrom = args[0], " ".join(args[1:])
1424
1424
1425 #print 'rng',ranges # dbg
1425 #print 'rng',ranges # dbg
1426 try:
1426 try:
1427 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1427 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1428 except (ValueError, TypeError) as e:
1428 except (ValueError, TypeError) as e:
1429 print(e.args[0])
1429 print(e.args[0])
1430 return
1430 return
1431 macro = Macro(lines)
1431 macro = Macro(lines)
1432 self.shell.define_macro(name, macro)
1432 self.shell.define_macro(name, macro)
1433 if not ( 'q' in opts) :
1433 if not ( 'q' in opts) :
1434 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1434 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1435 print('=== Macro contents: ===')
1435 print('=== Macro contents: ===')
1436 print(macro, end=' ')
1436 print(macro, end=' ')
1437
1437
1438 @magic_arguments.magic_arguments()
1438 @magic_arguments.magic_arguments()
1439 @magic_arguments.argument('output', type=str, default='', nargs='?',
1439 @magic_arguments.argument('output', type=str, default='', nargs='?',
1440 help="""The name of the variable in which to store output.
1440 help="""The name of the variable in which to store output.
1441 This is a utils.io.CapturedIO object with stdout/err attributes
1441 This is a utils.io.CapturedIO object with stdout/err attributes
1442 for the text of the captured output.
1442 for the text of the captured output.
1443
1443
1444 CapturedOutput also has a show() method for displaying the output,
1444 CapturedOutput also has a show() method for displaying the output,
1445 and __call__ as well, so you can use that to quickly display the
1445 and __call__ as well, so you can use that to quickly display the
1446 output.
1446 output.
1447
1447
1448 If unspecified, captured output is discarded.
1448 If unspecified, captured output is discarded.
1449 """
1449 """
1450 )
1450 )
1451 @magic_arguments.argument('--no-stderr', action="store_true",
1451 @magic_arguments.argument('--no-stderr', action="store_true",
1452 help="""Don't capture stderr."""
1452 help="""Don't capture stderr."""
1453 )
1453 )
1454 @magic_arguments.argument('--no-stdout', action="store_true",
1454 @magic_arguments.argument('--no-stdout', action="store_true",
1455 help="""Don't capture stdout."""
1455 help="""Don't capture stdout."""
1456 )
1456 )
1457 @magic_arguments.argument('--no-display', action="store_true",
1457 @magic_arguments.argument('--no-display', action="store_true",
1458 help="""Don't capture IPython's rich display."""
1458 help="""Don't capture IPython's rich display."""
1459 )
1459 )
1460 @cell_magic
1460 @cell_magic
1461 def capture(self, line, cell):
1461 def capture(self, line, cell):
1462 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1462 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1463 args = magic_arguments.parse_argstring(self.capture, line)
1463 args = magic_arguments.parse_argstring(self.capture, line)
1464 out = not args.no_stdout
1464 out = not args.no_stdout
1465 err = not args.no_stderr
1465 err = not args.no_stderr
1466 disp = not args.no_display
1466 disp = not args.no_display
1467 with capture_output(out, err, disp) as io:
1467 with capture_output(out, err, disp) as io:
1468 self.shell.run_cell(cell)
1468 self.shell.run_cell(cell)
1469 if args.output:
1469 if args.output:
1470 self.shell.user_ns[args.output] = io
1470 self.shell.user_ns[args.output] = io
1471
1471
1472 def parse_breakpoint(text, current_file):
1472 def parse_breakpoint(text, current_file):
1473 '''Returns (file, line) for file:line and (current_file, line) for line'''
1473 '''Returns (file, line) for file:line and (current_file, line) for line'''
1474 colon = text.find(':')
1474 colon = text.find(':')
1475 if colon == -1:
1475 if colon == -1:
1476 return current_file, int(text)
1476 return current_file, int(text)
1477 else:
1477 else:
1478 return text[:colon], int(text[colon+1:])
1478 return text[:colon], int(text[colon+1:])
1479
1479
1480 def _format_time(timespan, precision=3):
1480 def _format_time(timespan, precision=3):
1481 """Formats the timespan in a human readable form"""
1481 """Formats the timespan in a human readable form"""
1482
1482
1483 if timespan >= 60.0:
1483 if timespan >= 60.0:
1484 # we have more than a minute, format that in a human readable form
1484 # we have more than a minute, format that in a human readable form
1485 # Idea from http://snipplr.com/view/5713/
1485 # Idea from http://snipplr.com/view/5713/
1486 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1486 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1487 time = []
1487 time = []
1488 leftover = timespan
1488 leftover = timespan
1489 for suffix, length in parts:
1489 for suffix, length in parts:
1490 value = int(leftover / length)
1490 value = int(leftover / length)
1491 if value > 0:
1491 if value > 0:
1492 leftover = leftover % length
1492 leftover = leftover % length
1493 time.append(u'%s%s' % (str(value), suffix))
1493 time.append(u'%s%s' % (str(value), suffix))
1494 if leftover < 1:
1494 if leftover < 1:
1495 break
1495 break
1496 return " ".join(time)
1496 return " ".join(time)
1497
1497
1498
1498
1499 # Unfortunately the unicode 'micro' symbol can cause problems in
1499 # Unfortunately the unicode 'micro' symbol can cause problems in
1500 # certain terminals.
1500 # certain terminals.
1501 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1501 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1502 # Try to prevent crashes by being more secure than it needs to
1502 # Try to prevent crashes by being more secure than it needs to
1503 # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
1503 # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
1504 units = [u"s", u"ms",u'us',"ns"] # the save value
1504 units = [u"s", u"ms",u'us',"ns"] # the save value
1505 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1505 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1506 try:
1506 try:
1507 u'\xb5'.encode(sys.stdout.encoding)
1507 u'\xb5'.encode(sys.stdout.encoding)
1508 units = [u"s", u"ms",u'\xb5s',"ns"]
1508 units = [u"s", u"ms",u'\xb5s',"ns"]
1509 except:
1509 except:
1510 pass
1510 pass
1511 scaling = [1, 1e3, 1e6, 1e9]
1511 scaling = [1, 1e3, 1e6, 1e9]
1512
1512
1513 if timespan > 0.0:
1513 if timespan > 0.0:
1514 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1514 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1515 else:
1515 else:
1516 order = 3
1516 order = 3
1517 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
1517 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
General Comments 0
You need to be logged in to leave comments. Login now