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