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