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