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