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