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