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