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