##// END OF EJS Templates
add %%capture cell magic
MinRK -
Show More
@@ -1,990 +1,1016 b''
1 """Implementation of execution-related magic functions.
1 """Implementation of execution-related magic functions.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
4 # Copyright (c) 2012 The IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 # Stdlib
15 # Stdlib
16 import __builtin__ as builtin_mod
16 import __builtin__ as builtin_mod
17 import bdb
17 import bdb
18 import os
18 import os
19 import sys
19 import sys
20 import time
20 import time
21 from StringIO import StringIO
21 from StringIO import StringIO
22
22
23 # cProfile was added in Python2.5
23 # cProfile was added in Python2.5
24 try:
24 try:
25 import cProfile as profile
25 import cProfile as profile
26 import pstats
26 import pstats
27 except ImportError:
27 except ImportError:
28 # profile isn't bundled by default in Debian for license reasons
28 # profile isn't bundled by default in Debian for license reasons
29 try:
29 try:
30 import profile, pstats
30 import profile, pstats
31 except ImportError:
31 except ImportError:
32 profile = pstats = None
32 profile = pstats = None
33
33
34 # Our own packages
34 # Our own packages
35 from IPython.core import debugger, oinspect
35 from IPython.core import debugger, oinspect
36 from IPython.core import magic_arguments
36 from IPython.core import page
37 from IPython.core import page
37 from IPython.core.error import UsageError
38 from IPython.core.error import UsageError
38 from IPython.core.macro import Macro
39 from IPython.core.macro import Macro
39 from IPython.core.magic import (Magics, magics_class, line_magic,
40 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
40 line_cell_magic, on_off, needs_local_scope)
41 line_cell_magic, on_off, needs_local_scope)
41 from IPython.testing.skipdoctest import skip_doctest
42 from IPython.testing.skipdoctest import skip_doctest
42 from IPython.utils import py3compat
43 from IPython.utils import py3compat
44 from IPython.utils.io import capture_output
43 from IPython.utils.ipstruct import Struct
45 from IPython.utils.ipstruct import Struct
44 from IPython.utils.module_paths import find_mod
46 from IPython.utils.module_paths import find_mod
45 from IPython.utils.path import get_py_filename, unquote_filename
47 from IPython.utils.path import get_py_filename, unquote_filename
46 from IPython.utils.timing import clock, clock2
48 from IPython.utils.timing import clock, clock2
47 from IPython.utils.warn import warn, error
49 from IPython.utils.warn import warn, error
48
50
49 #-----------------------------------------------------------------------------
51 #-----------------------------------------------------------------------------
50 # Magic implementation classes
52 # Magic implementation classes
51 #-----------------------------------------------------------------------------
53 #-----------------------------------------------------------------------------
52
54
53 @magics_class
55 @magics_class
54 class ExecutionMagics(Magics):
56 class ExecutionMagics(Magics):
55 """Magics related to code execution, debugging, profiling, etc.
57 """Magics related to code execution, debugging, profiling, etc.
56
58
57 """
59 """
58
60
59 def __init__(self, shell):
61 def __init__(self, shell):
60 super(ExecutionMagics, self).__init__(shell)
62 super(ExecutionMagics, self).__init__(shell)
61 if profile is None:
63 if profile is None:
62 self.prun = self.profile_missing_notice
64 self.prun = self.profile_missing_notice
63 # Default execution function used to actually run user code.
65 # Default execution function used to actually run user code.
64 self.default_runner = None
66 self.default_runner = None
65
67
66 def profile_missing_notice(self, *args, **kwargs):
68 def profile_missing_notice(self, *args, **kwargs):
67 error("""\
69 error("""\
68 The profile module could not be found. It has been removed from the standard
70 The profile module could not be found. It has been removed from the standard
69 python packages because of its non-free license. To use profiling, install the
71 python packages because of its non-free license. To use profiling, install the
70 python-profiler package from non-free.""")
72 python-profiler package from non-free.""")
71
73
72 @skip_doctest
74 @skip_doctest
73 @line_cell_magic
75 @line_cell_magic
74 def prun(self, parameter_s='', cell=None, user_mode=True,
76 def prun(self, parameter_s='', cell=None, user_mode=True,
75 opts=None,arg_lst=None,prog_ns=None):
77 opts=None,arg_lst=None,prog_ns=None):
76
78
77 """Run a statement through the python code profiler.
79 """Run a statement through the python code profiler.
78
80
79 Usage, in line mode:
81 Usage, in line mode:
80 %prun [options] statement
82 %prun [options] statement
81
83
82 Usage, in cell mode:
84 Usage, in cell mode:
83 %%prun [options] [statement]
85 %%prun [options] [statement]
84 code...
86 code...
85 code...
87 code...
86
88
87 In cell mode, the additional code lines are appended to the (possibly
89 In cell mode, the additional code lines are appended to the (possibly
88 empty) statement in the first line. Cell mode allows you to easily
90 empty) statement in the first line. Cell mode allows you to easily
89 profile multiline blocks without having to put them in a separate
91 profile multiline blocks without having to put them in a separate
90 function.
92 function.
91
93
92 The given statement (which doesn't require quote marks) is run via the
94 The given statement (which doesn't require quote marks) is run via the
93 python profiler in a manner similar to the profile.run() function.
95 python profiler in a manner similar to the profile.run() function.
94 Namespaces are internally managed to work correctly; profile.run
96 Namespaces are internally managed to work correctly; profile.run
95 cannot be used in IPython because it makes certain assumptions about
97 cannot be used in IPython because it makes certain assumptions about
96 namespaces which do not hold under IPython.
98 namespaces which do not hold under IPython.
97
99
98 Options:
100 Options:
99
101
100 -l <limit>: you can place restrictions on what or how much of the
102 -l <limit>: you can place restrictions on what or how much of the
101 profile gets printed. The limit value can be:
103 profile gets printed. The limit value can be:
102
104
103 * A string: only information for function names containing this string
105 * A string: only information for function names containing this string
104 is printed.
106 is printed.
105
107
106 * An integer: only these many lines are printed.
108 * An integer: only these many lines are printed.
107
109
108 * A float (between 0 and 1): this fraction of the report is printed
110 * A float (between 0 and 1): this fraction of the report is printed
109 (for example, use a limit of 0.4 to see the topmost 40% only).
111 (for example, use a limit of 0.4 to see the topmost 40% only).
110
112
111 You can combine several limits with repeated use of the option. For
113 You can combine several limits with repeated use of the option. For
112 example, '-l __init__ -l 5' will print only the topmost 5 lines of
114 example, '-l __init__ -l 5' will print only the topmost 5 lines of
113 information about class constructors.
115 information about class constructors.
114
116
115 -r: return the pstats.Stats object generated by the profiling. This
117 -r: return the pstats.Stats object generated by the profiling. This
116 object has all the information about the profile in it, and you can
118 object has all the information about the profile in it, and you can
117 later use it for further analysis or in other functions.
119 later use it for further analysis or in other functions.
118
120
119 -s <key>: sort profile by given key. You can provide more than one key
121 -s <key>: sort profile by given key. You can provide more than one key
120 by using the option several times: '-s key1 -s key2 -s key3...'. The
122 by using the option several times: '-s key1 -s key2 -s key3...'. The
121 default sorting key is 'time'.
123 default sorting key is 'time'.
122
124
123 The following is copied verbatim from the profile documentation
125 The following is copied verbatim from the profile documentation
124 referenced below:
126 referenced below:
125
127
126 When more than one key is provided, additional keys are used as
128 When more than one key is provided, additional keys are used as
127 secondary criteria when the there is equality in all keys selected
129 secondary criteria when the there is equality in all keys selected
128 before them.
130 before them.
129
131
130 Abbreviations can be used for any key names, as long as the
132 Abbreviations can be used for any key names, as long as the
131 abbreviation is unambiguous. The following are the keys currently
133 abbreviation is unambiguous. The following are the keys currently
132 defined:
134 defined:
133
135
134 Valid Arg Meaning
136 Valid Arg Meaning
135 "calls" call count
137 "calls" call count
136 "cumulative" cumulative time
138 "cumulative" cumulative time
137 "file" file name
139 "file" file name
138 "module" file name
140 "module" file name
139 "pcalls" primitive call count
141 "pcalls" primitive call count
140 "line" line number
142 "line" line number
141 "name" function name
143 "name" function name
142 "nfl" name/file/line
144 "nfl" name/file/line
143 "stdname" standard name
145 "stdname" standard name
144 "time" internal time
146 "time" internal time
145
147
146 Note that all sorts on statistics are in descending order (placing
148 Note that all sorts on statistics are in descending order (placing
147 most time consuming items first), where as name, file, and line number
149 most time consuming items first), where as name, file, and line number
148 searches are in ascending order (i.e., alphabetical). The subtle
150 searches are in ascending order (i.e., alphabetical). The subtle
149 distinction between "nfl" and "stdname" is that the standard name is a
151 distinction between "nfl" and "stdname" is that the standard name is a
150 sort of the name as printed, which means that the embedded line
152 sort of the name as printed, which means that the embedded line
151 numbers get compared in an odd way. For example, lines 3, 20, and 40
153 numbers get compared in an odd way. For example, lines 3, 20, and 40
152 would (if the file names were the same) appear in the string order
154 would (if the file names were the same) appear in the string order
153 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
155 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
154 line numbers. In fact, sort_stats("nfl") is the same as
156 line numbers. In fact, sort_stats("nfl") is the same as
155 sort_stats("name", "file", "line").
157 sort_stats("name", "file", "line").
156
158
157 -T <filename>: save profile results as shown on screen to a text
159 -T <filename>: save profile results as shown on screen to a text
158 file. The profile is still shown on screen.
160 file. The profile is still shown on screen.
159
161
160 -D <filename>: save (via dump_stats) profile statistics to given
162 -D <filename>: save (via dump_stats) profile statistics to given
161 filename. This data is in a format understood by the pstats module, and
163 filename. This data is in a format understood by the pstats module, and
162 is generated by a call to the dump_stats() method of profile
164 is generated by a call to the dump_stats() method of profile
163 objects. The profile is still shown on screen.
165 objects. The profile is still shown on screen.
164
166
165 -q: suppress output to the pager. Best used with -T and/or -D above.
167 -q: suppress output to the pager. Best used with -T and/or -D above.
166
168
167 If you want to run complete programs under the profiler's control, use
169 If you want to run complete programs under the profiler's control, use
168 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
170 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
169 contains profiler specific options as described here.
171 contains profiler specific options as described here.
170
172
171 You can read the complete documentation for the profile module with::
173 You can read the complete documentation for the profile module with::
172
174
173 In [1]: import profile; profile.help()
175 In [1]: import profile; profile.help()
174 """
176 """
175
177
176 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
178 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
177
179
178 if user_mode: # regular user call
180 if user_mode: # regular user call
179 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
181 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
180 list_all=True, posix=False)
182 list_all=True, posix=False)
181 namespace = self.shell.user_ns
183 namespace = self.shell.user_ns
182 if cell is not None:
184 if cell is not None:
183 arg_str += '\n' + cell
185 arg_str += '\n' + cell
184 else: # called to run a program by %run -p
186 else: # called to run a program by %run -p
185 try:
187 try:
186 filename = get_py_filename(arg_lst[0])
188 filename = get_py_filename(arg_lst[0])
187 except IOError as e:
189 except IOError as e:
188 try:
190 try:
189 msg = str(e)
191 msg = str(e)
190 except UnicodeError:
192 except UnicodeError:
191 msg = e.message
193 msg = e.message
192 error(msg)
194 error(msg)
193 return
195 return
194
196
195 arg_str = 'execfile(filename,prog_ns)'
197 arg_str = 'execfile(filename,prog_ns)'
196 namespace = {
198 namespace = {
197 'execfile': self.shell.safe_execfile,
199 'execfile': self.shell.safe_execfile,
198 'prog_ns': prog_ns,
200 'prog_ns': prog_ns,
199 'filename': filename
201 'filename': filename
200 }
202 }
201
203
202 opts.merge(opts_def)
204 opts.merge(opts_def)
203
205
204 prof = profile.Profile()
206 prof = profile.Profile()
205 try:
207 try:
206 prof = prof.runctx(arg_str,namespace,namespace)
208 prof = prof.runctx(arg_str,namespace,namespace)
207 sys_exit = ''
209 sys_exit = ''
208 except SystemExit:
210 except SystemExit:
209 sys_exit = """*** SystemExit exception caught in code being profiled."""
211 sys_exit = """*** SystemExit exception caught in code being profiled."""
210
212
211 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
213 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
212
214
213 lims = opts.l
215 lims = opts.l
214 if lims:
216 if lims:
215 lims = [] # rebuild lims with ints/floats/strings
217 lims = [] # rebuild lims with ints/floats/strings
216 for lim in opts.l:
218 for lim in opts.l:
217 try:
219 try:
218 lims.append(int(lim))
220 lims.append(int(lim))
219 except ValueError:
221 except ValueError:
220 try:
222 try:
221 lims.append(float(lim))
223 lims.append(float(lim))
222 except ValueError:
224 except ValueError:
223 lims.append(lim)
225 lims.append(lim)
224
226
225 # Trap output.
227 # Trap output.
226 stdout_trap = StringIO()
228 stdout_trap = StringIO()
227
229
228 if hasattr(stats,'stream'):
230 if hasattr(stats,'stream'):
229 # In newer versions of python, the stats object has a 'stream'
231 # In newer versions of python, the stats object has a 'stream'
230 # attribute to write into.
232 # attribute to write into.
231 stats.stream = stdout_trap
233 stats.stream = stdout_trap
232 stats.print_stats(*lims)
234 stats.print_stats(*lims)
233 else:
235 else:
234 # For older versions, we manually redirect stdout during printing
236 # For older versions, we manually redirect stdout during printing
235 sys_stdout = sys.stdout
237 sys_stdout = sys.stdout
236 try:
238 try:
237 sys.stdout = stdout_trap
239 sys.stdout = stdout_trap
238 stats.print_stats(*lims)
240 stats.print_stats(*lims)
239 finally:
241 finally:
240 sys.stdout = sys_stdout
242 sys.stdout = sys_stdout
241
243
242 output = stdout_trap.getvalue()
244 output = stdout_trap.getvalue()
243 output = output.rstrip()
245 output = output.rstrip()
244
246
245 if 'q' not in opts:
247 if 'q' not in opts:
246 page.page(output)
248 page.page(output)
247 print sys_exit,
249 print sys_exit,
248
250
249 dump_file = opts.D[0]
251 dump_file = opts.D[0]
250 text_file = opts.T[0]
252 text_file = opts.T[0]
251 if dump_file:
253 if dump_file:
252 dump_file = unquote_filename(dump_file)
254 dump_file = unquote_filename(dump_file)
253 prof.dump_stats(dump_file)
255 prof.dump_stats(dump_file)
254 print '\n*** Profile stats marshalled to file',\
256 print '\n*** Profile stats marshalled to file',\
255 `dump_file`+'.',sys_exit
257 `dump_file`+'.',sys_exit
256 if text_file:
258 if text_file:
257 text_file = unquote_filename(text_file)
259 text_file = unquote_filename(text_file)
258 pfile = open(text_file,'w')
260 pfile = open(text_file,'w')
259 pfile.write(output)
261 pfile.write(output)
260 pfile.close()
262 pfile.close()
261 print '\n*** Profile printout saved to text file',\
263 print '\n*** Profile printout saved to text file',\
262 `text_file`+'.',sys_exit
264 `text_file`+'.',sys_exit
263
265
264 if opts.has_key('r'):
266 if opts.has_key('r'):
265 return stats
267 return stats
266 else:
268 else:
267 return None
269 return None
268
270
269 @line_magic
271 @line_magic
270 def pdb(self, parameter_s=''):
272 def pdb(self, parameter_s=''):
271 """Control the automatic calling of the pdb interactive debugger.
273 """Control the automatic calling of the pdb interactive debugger.
272
274
273 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
275 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
274 argument it works as a toggle.
276 argument it works as a toggle.
275
277
276 When an exception is triggered, IPython can optionally call the
278 When an exception is triggered, IPython can optionally call the
277 interactive pdb debugger after the traceback printout. %pdb toggles
279 interactive pdb debugger after the traceback printout. %pdb toggles
278 this feature on and off.
280 this feature on and off.
279
281
280 The initial state of this feature is set in your configuration
282 The initial state of this feature is set in your configuration
281 file (the option is ``InteractiveShell.pdb``).
283 file (the option is ``InteractiveShell.pdb``).
282
284
283 If you want to just activate the debugger AFTER an exception has fired,
285 If you want to just activate the debugger AFTER an exception has fired,
284 without having to type '%pdb on' and rerunning your code, you can use
286 without having to type '%pdb on' and rerunning your code, you can use
285 the %debug magic."""
287 the %debug magic."""
286
288
287 par = parameter_s.strip().lower()
289 par = parameter_s.strip().lower()
288
290
289 if par:
291 if par:
290 try:
292 try:
291 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
293 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
292 except KeyError:
294 except KeyError:
293 print ('Incorrect argument. Use on/1, off/0, '
295 print ('Incorrect argument. Use on/1, off/0, '
294 'or nothing for a toggle.')
296 'or nothing for a toggle.')
295 return
297 return
296 else:
298 else:
297 # toggle
299 # toggle
298 new_pdb = not self.shell.call_pdb
300 new_pdb = not self.shell.call_pdb
299
301
300 # set on the shell
302 # set on the shell
301 self.shell.call_pdb = new_pdb
303 self.shell.call_pdb = new_pdb
302 print 'Automatic pdb calling has been turned',on_off(new_pdb)
304 print 'Automatic pdb calling has been turned',on_off(new_pdb)
303
305
304 @line_magic
306 @line_magic
305 def debug(self, parameter_s=''):
307 def debug(self, parameter_s=''):
306 """Activate the interactive debugger in post-mortem mode.
308 """Activate the interactive debugger in post-mortem mode.
307
309
308 If an exception has just occurred, this lets you inspect its stack
310 If an exception has just occurred, this lets you inspect its stack
309 frames interactively. Note that this will always work only on the last
311 frames interactively. Note that this will always work only on the last
310 traceback that occurred, so you must call this quickly after an
312 traceback that occurred, so you must call this quickly after an
311 exception that you wish to inspect has fired, because if another one
313 exception that you wish to inspect has fired, because if another one
312 occurs, it clobbers the previous one.
314 occurs, it clobbers the previous one.
313
315
314 If you want IPython to automatically do this on every exception, see
316 If you want IPython to automatically do this on every exception, see
315 the %pdb magic for more details.
317 the %pdb magic for more details.
316 """
318 """
317 self.shell.debugger(force=True)
319 self.shell.debugger(force=True)
318
320
319 @line_magic
321 @line_magic
320 def tb(self, s):
322 def tb(self, s):
321 """Print the last traceback with the currently active exception mode.
323 """Print the last traceback with the currently active exception mode.
322
324
323 See %xmode for changing exception reporting modes."""
325 See %xmode for changing exception reporting modes."""
324 self.shell.showtraceback()
326 self.shell.showtraceback()
325
327
326 @skip_doctest
328 @skip_doctest
327 @line_magic
329 @line_magic
328 def run(self, parameter_s='', runner=None,
330 def run(self, parameter_s='', runner=None,
329 file_finder=get_py_filename):
331 file_finder=get_py_filename):
330 """Run the named file inside IPython as a program.
332 """Run the named file inside IPython as a program.
331
333
332 Usage:\\
334 Usage:\\
333 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
335 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
334
336
335 Parameters after the filename are passed as command-line arguments to
337 Parameters after the filename are passed as command-line arguments to
336 the program (put in sys.argv). Then, control returns to IPython's
338 the program (put in sys.argv). Then, control returns to IPython's
337 prompt.
339 prompt.
338
340
339 This is similar to running at a system prompt:\\
341 This is similar to running at a system prompt:\\
340 $ python file args\\
342 $ python file args\\
341 but with the advantage of giving you IPython's tracebacks, and of
343 but with the advantage of giving you IPython's tracebacks, and of
342 loading all variables into your interactive namespace for further use
344 loading all variables into your interactive namespace for further use
343 (unless -p is used, see below).
345 (unless -p is used, see below).
344
346
345 The file is executed in a namespace initially consisting only of
347 The file is executed in a namespace initially consisting only of
346 __name__=='__main__' and sys.argv constructed as indicated. It thus
348 __name__=='__main__' and sys.argv constructed as indicated. It thus
347 sees its environment as if it were being run as a stand-alone program
349 sees its environment as if it were being run as a stand-alone program
348 (except for sharing global objects such as previously imported
350 (except for sharing global objects such as previously imported
349 modules). But after execution, the IPython interactive namespace gets
351 modules). But after execution, the IPython interactive namespace gets
350 updated with all variables defined in the program (except for __name__
352 updated with all variables defined in the program (except for __name__
351 and sys.argv). This allows for very convenient loading of code for
353 and sys.argv). This allows for very convenient loading of code for
352 interactive work, while giving each program a 'clean sheet' to run in.
354 interactive work, while giving each program a 'clean sheet' to run in.
353
355
354 Options:
356 Options:
355
357
356 -n: __name__ is NOT set to '__main__', but to the running file's name
358 -n: __name__ is NOT set to '__main__', but to the running file's name
357 without extension (as python does under import). This allows running
359 without extension (as python does under import). This allows running
358 scripts and reloading the definitions in them without calling code
360 scripts and reloading the definitions in them without calling code
359 protected by an ' if __name__ == "__main__" ' clause.
361 protected by an ' if __name__ == "__main__" ' clause.
360
362
361 -i: run the file in IPython's namespace instead of an empty one. This
363 -i: run the file in IPython's namespace instead of an empty one. This
362 is useful if you are experimenting with code written in a text editor
364 is useful if you are experimenting with code written in a text editor
363 which depends on variables defined interactively.
365 which depends on variables defined interactively.
364
366
365 -e: ignore sys.exit() calls or SystemExit exceptions in the script
367 -e: ignore sys.exit() calls or SystemExit exceptions in the script
366 being run. This is particularly useful if IPython is being used to
368 being run. This is particularly useful if IPython is being used to
367 run unittests, which always exit with a sys.exit() call. In such
369 run unittests, which always exit with a sys.exit() call. In such
368 cases you are interested in the output of the test results, not in
370 cases you are interested in the output of the test results, not in
369 seeing a traceback of the unittest module.
371 seeing a traceback of the unittest module.
370
372
371 -t: print timing information at the end of the run. IPython will give
373 -t: print timing information at the end of the run. IPython will give
372 you an estimated CPU time consumption for your script, which under
374 you an estimated CPU time consumption for your script, which under
373 Unix uses the resource module to avoid the wraparound problems of
375 Unix uses the resource module to avoid the wraparound problems of
374 time.clock(). Under Unix, an estimate of time spent on system tasks
376 time.clock(). Under Unix, an estimate of time spent on system tasks
375 is also given (for Windows platforms this is reported as 0.0).
377 is also given (for Windows platforms this is reported as 0.0).
376
378
377 If -t is given, an additional -N<N> option can be given, where <N>
379 If -t is given, an additional -N<N> option can be given, where <N>
378 must be an integer indicating how many times you want the script to
380 must be an integer indicating how many times you want the script to
379 run. The final timing report will include total and per run results.
381 run. The final timing report will include total and per run results.
380
382
381 For example (testing the script uniq_stable.py)::
383 For example (testing the script uniq_stable.py)::
382
384
383 In [1]: run -t uniq_stable
385 In [1]: run -t uniq_stable
384
386
385 IPython CPU timings (estimated):\\
387 IPython CPU timings (estimated):\\
386 User : 0.19597 s.\\
388 User : 0.19597 s.\\
387 System: 0.0 s.\\
389 System: 0.0 s.\\
388
390
389 In [2]: run -t -N5 uniq_stable
391 In [2]: run -t -N5 uniq_stable
390
392
391 IPython CPU timings (estimated):\\
393 IPython CPU timings (estimated):\\
392 Total runs performed: 5\\
394 Total runs performed: 5\\
393 Times : Total Per run\\
395 Times : Total Per run\\
394 User : 0.910862 s, 0.1821724 s.\\
396 User : 0.910862 s, 0.1821724 s.\\
395 System: 0.0 s, 0.0 s.
397 System: 0.0 s, 0.0 s.
396
398
397 -d: run your program under the control of pdb, the Python debugger.
399 -d: run your program under the control of pdb, the Python debugger.
398 This allows you to execute your program step by step, watch variables,
400 This allows you to execute your program step by step, watch variables,
399 etc. Internally, what IPython does is similar to calling:
401 etc. Internally, what IPython does is similar to calling:
400
402
401 pdb.run('execfile("YOURFILENAME")')
403 pdb.run('execfile("YOURFILENAME")')
402
404
403 with a breakpoint set on line 1 of your file. You can change the line
405 with a breakpoint set on line 1 of your file. You can change the line
404 number for this automatic breakpoint to be <N> by using the -bN option
406 number for this automatic breakpoint to be <N> by using the -bN option
405 (where N must be an integer). For example::
407 (where N must be an integer). For example::
406
408
407 %run -d -b40 myscript
409 %run -d -b40 myscript
408
410
409 will set the first breakpoint at line 40 in myscript.py. Note that
411 will set the first breakpoint at line 40 in myscript.py. Note that
410 the first breakpoint must be set on a line which actually does
412 the first breakpoint must be set on a line which actually does
411 something (not a comment or docstring) for it to stop execution.
413 something (not a comment or docstring) for it to stop execution.
412
414
413 When the pdb debugger starts, you will see a (Pdb) prompt. You must
415 When the pdb debugger starts, you will see a (Pdb) prompt. You must
414 first enter 'c' (without quotes) to start execution up to the first
416 first enter 'c' (without quotes) to start execution up to the first
415 breakpoint.
417 breakpoint.
416
418
417 Entering 'help' gives information about the use of the debugger. You
419 Entering 'help' gives information about the use of the debugger. You
418 can easily see pdb's full documentation with "import pdb;pdb.help()"
420 can easily see pdb's full documentation with "import pdb;pdb.help()"
419 at a prompt.
421 at a prompt.
420
422
421 -p: run program under the control of the Python profiler module (which
423 -p: run program under the control of the Python profiler module (which
422 prints a detailed report of execution times, function calls, etc).
424 prints a detailed report of execution times, function calls, etc).
423
425
424 You can pass other options after -p which affect the behavior of the
426 You can pass other options after -p which affect the behavior of the
425 profiler itself. See the docs for %prun for details.
427 profiler itself. See the docs for %prun for details.
426
428
427 In this mode, the program's variables do NOT propagate back to the
429 In this mode, the program's variables do NOT propagate back to the
428 IPython interactive namespace (because they remain in the namespace
430 IPython interactive namespace (because they remain in the namespace
429 where the profiler executes them).
431 where the profiler executes them).
430
432
431 Internally this triggers a call to %prun, see its documentation for
433 Internally this triggers a call to %prun, see its documentation for
432 details on the options available specifically for profiling.
434 details on the options available specifically for profiling.
433
435
434 There is one special usage for which the text above doesn't apply:
436 There is one special usage for which the text above doesn't apply:
435 if the filename ends with .ipy, the file is run as ipython script,
437 if the filename ends with .ipy, the file is run as ipython script,
436 just as if the commands were written on IPython prompt.
438 just as if the commands were written on IPython prompt.
437
439
438 -m: specify module name to load instead of script path. Similar to
440 -m: specify module name to load instead of script path. Similar to
439 the -m option for the python interpreter. Use this option last if you
441 the -m option for the python interpreter. Use this option last if you
440 want to combine with other %run options. Unlike the python interpreter
442 want to combine with other %run options. Unlike the python interpreter
441 only source modules are allowed no .pyc or .pyo files.
443 only source modules are allowed no .pyc or .pyo files.
442 For example::
444 For example::
443
445
444 %run -m example
446 %run -m example
445
447
446 will run the example module.
448 will run the example module.
447
449
448 """
450 """
449
451
450 # get arguments and set sys.argv for program to be run.
452 # get arguments and set sys.argv for program to be run.
451 opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:',
453 opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:',
452 mode='list', list_all=1)
454 mode='list', list_all=1)
453 if "m" in opts:
455 if "m" in opts:
454 modulename = opts["m"][0]
456 modulename = opts["m"][0]
455 modpath = find_mod(modulename)
457 modpath = find_mod(modulename)
456 if modpath is None:
458 if modpath is None:
457 warn('%r is not a valid modulename on sys.path'%modulename)
459 warn('%r is not a valid modulename on sys.path'%modulename)
458 return
460 return
459 arg_lst = [modpath] + arg_lst
461 arg_lst = [modpath] + arg_lst
460 try:
462 try:
461 filename = file_finder(arg_lst[0])
463 filename = file_finder(arg_lst[0])
462 except IndexError:
464 except IndexError:
463 warn('you must provide at least a filename.')
465 warn('you must provide at least a filename.')
464 print '\n%run:\n', oinspect.getdoc(self.run)
466 print '\n%run:\n', oinspect.getdoc(self.run)
465 return
467 return
466 except IOError as e:
468 except IOError as e:
467 try:
469 try:
468 msg = str(e)
470 msg = str(e)
469 except UnicodeError:
471 except UnicodeError:
470 msg = e.message
472 msg = e.message
471 error(msg)
473 error(msg)
472 return
474 return
473
475
474 if filename.lower().endswith('.ipy'):
476 if filename.lower().endswith('.ipy'):
475 self.shell.safe_execfile_ipy(filename)
477 self.shell.safe_execfile_ipy(filename)
476 return
478 return
477
479
478 # Control the response to exit() calls made by the script being run
480 # Control the response to exit() calls made by the script being run
479 exit_ignore = 'e' in opts
481 exit_ignore = 'e' in opts
480
482
481 # Make sure that the running script gets a proper sys.argv as if it
483 # Make sure that the running script gets a proper sys.argv as if it
482 # were run from a system shell.
484 # were run from a system shell.
483 save_argv = sys.argv # save it for later restoring
485 save_argv = sys.argv # save it for later restoring
484
486
485 # simulate shell expansion on arguments, at least tilde expansion
487 # simulate shell expansion on arguments, at least tilde expansion
486 args = [ os.path.expanduser(a) for a in arg_lst[1:] ]
488 args = [ os.path.expanduser(a) for a in arg_lst[1:] ]
487
489
488 sys.argv = [filename] + args # put in the proper filename
490 sys.argv = [filename] + args # put in the proper filename
489 # protect sys.argv from potential unicode strings on Python 2:
491 # protect sys.argv from potential unicode strings on Python 2:
490 if not py3compat.PY3:
492 if not py3compat.PY3:
491 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
493 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
492
494
493 if 'i' in opts:
495 if 'i' in opts:
494 # Run in user's interactive namespace
496 # Run in user's interactive namespace
495 prog_ns = self.shell.user_ns
497 prog_ns = self.shell.user_ns
496 __name__save = self.shell.user_ns['__name__']
498 __name__save = self.shell.user_ns['__name__']
497 prog_ns['__name__'] = '__main__'
499 prog_ns['__name__'] = '__main__'
498 main_mod = self.shell.new_main_mod(prog_ns)
500 main_mod = self.shell.new_main_mod(prog_ns)
499 else:
501 else:
500 # Run in a fresh, empty namespace
502 # Run in a fresh, empty namespace
501 if 'n' in opts:
503 if 'n' in opts:
502 name = os.path.splitext(os.path.basename(filename))[0]
504 name = os.path.splitext(os.path.basename(filename))[0]
503 else:
505 else:
504 name = '__main__'
506 name = '__main__'
505
507
506 main_mod = self.shell.new_main_mod()
508 main_mod = self.shell.new_main_mod()
507 prog_ns = main_mod.__dict__
509 prog_ns = main_mod.__dict__
508 prog_ns['__name__'] = name
510 prog_ns['__name__'] = name
509
511
510 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
512 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
511 # set the __file__ global in the script's namespace
513 # set the __file__ global in the script's namespace
512 prog_ns['__file__'] = filename
514 prog_ns['__file__'] = filename
513
515
514 # pickle fix. See interactiveshell for an explanation. But we need to
516 # pickle fix. See interactiveshell for an explanation. But we need to
515 # make sure that, if we overwrite __main__, we replace it at the end
517 # make sure that, if we overwrite __main__, we replace it at the end
516 main_mod_name = prog_ns['__name__']
518 main_mod_name = prog_ns['__name__']
517
519
518 if main_mod_name == '__main__':
520 if main_mod_name == '__main__':
519 restore_main = sys.modules['__main__']
521 restore_main = sys.modules['__main__']
520 else:
522 else:
521 restore_main = False
523 restore_main = False
522
524
523 # This needs to be undone at the end to prevent holding references to
525 # This needs to be undone at the end to prevent holding references to
524 # every single object ever created.
526 # every single object ever created.
525 sys.modules[main_mod_name] = main_mod
527 sys.modules[main_mod_name] = main_mod
526
528
527 try:
529 try:
528 stats = None
530 stats = None
529 with self.shell.readline_no_record:
531 with self.shell.readline_no_record:
530 if 'p' in opts:
532 if 'p' in opts:
531 stats = self.prun('', None, False, opts, arg_lst, prog_ns)
533 stats = self.prun('', None, False, opts, arg_lst, prog_ns)
532 else:
534 else:
533 if 'd' in opts:
535 if 'd' in opts:
534 deb = debugger.Pdb(self.shell.colors)
536 deb = debugger.Pdb(self.shell.colors)
535 # reset Breakpoint state, which is moronically kept
537 # reset Breakpoint state, which is moronically kept
536 # in a class
538 # in a class
537 bdb.Breakpoint.next = 1
539 bdb.Breakpoint.next = 1
538 bdb.Breakpoint.bplist = {}
540 bdb.Breakpoint.bplist = {}
539 bdb.Breakpoint.bpbynumber = [None]
541 bdb.Breakpoint.bpbynumber = [None]
540 # Set an initial breakpoint to stop execution
542 # Set an initial breakpoint to stop execution
541 maxtries = 10
543 maxtries = 10
542 bp = int(opts.get('b', [1])[0])
544 bp = int(opts.get('b', [1])[0])
543 checkline = deb.checkline(filename, bp)
545 checkline = deb.checkline(filename, bp)
544 if not checkline:
546 if not checkline:
545 for bp in range(bp + 1, bp + maxtries + 1):
547 for bp in range(bp + 1, bp + maxtries + 1):
546 if deb.checkline(filename, bp):
548 if deb.checkline(filename, bp):
547 break
549 break
548 else:
550 else:
549 msg = ("\nI failed to find a valid line to set "
551 msg = ("\nI failed to find a valid line to set "
550 "a breakpoint\n"
552 "a breakpoint\n"
551 "after trying up to line: %s.\n"
553 "after trying up to line: %s.\n"
552 "Please set a valid breakpoint manually "
554 "Please set a valid breakpoint manually "
553 "with the -b option." % bp)
555 "with the -b option." % bp)
554 error(msg)
556 error(msg)
555 return
557 return
556 # if we find a good linenumber, set the breakpoint
558 # if we find a good linenumber, set the breakpoint
557 deb.do_break('%s:%s' % (filename, bp))
559 deb.do_break('%s:%s' % (filename, bp))
558 # Start file run
560 # Start file run
559 print "NOTE: Enter 'c' at the",
561 print "NOTE: Enter 'c' at the",
560 print "%s prompt to start your script." % deb.prompt
562 print "%s prompt to start your script." % deb.prompt
561 ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns}
563 ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns}
562 try:
564 try:
563 deb.run('execfile("%s", prog_ns)' % filename, ns)
565 deb.run('execfile("%s", prog_ns)' % filename, ns)
564
566
565 except:
567 except:
566 etype, value, tb = sys.exc_info()
568 etype, value, tb = sys.exc_info()
567 # Skip three frames in the traceback: the %run one,
569 # Skip three frames in the traceback: the %run one,
568 # one inside bdb.py, and the command-line typed by the
570 # one inside bdb.py, and the command-line typed by the
569 # user (run by exec in pdb itself).
571 # user (run by exec in pdb itself).
570 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
572 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
571 else:
573 else:
572 if runner is None:
574 if runner is None:
573 runner = self.default_runner
575 runner = self.default_runner
574 if runner is None:
576 if runner is None:
575 runner = self.shell.safe_execfile
577 runner = self.shell.safe_execfile
576 if 't' in opts:
578 if 't' in opts:
577 # timed execution
579 # timed execution
578 try:
580 try:
579 nruns = int(opts['N'][0])
581 nruns = int(opts['N'][0])
580 if nruns < 1:
582 if nruns < 1:
581 error('Number of runs must be >=1')
583 error('Number of runs must be >=1')
582 return
584 return
583 except (KeyError):
585 except (KeyError):
584 nruns = 1
586 nruns = 1
585 twall0 = time.time()
587 twall0 = time.time()
586 if nruns == 1:
588 if nruns == 1:
587 t0 = clock2()
589 t0 = clock2()
588 runner(filename, prog_ns, prog_ns,
590 runner(filename, prog_ns, prog_ns,
589 exit_ignore=exit_ignore)
591 exit_ignore=exit_ignore)
590 t1 = clock2()
592 t1 = clock2()
591 t_usr = t1[0] - t0[0]
593 t_usr = t1[0] - t0[0]
592 t_sys = t1[1] - t0[1]
594 t_sys = t1[1] - t0[1]
593 print "\nIPython CPU timings (estimated):"
595 print "\nIPython CPU timings (estimated):"
594 print " User : %10.2f s." % t_usr
596 print " User : %10.2f s." % t_usr
595 print " System : %10.2f s." % t_sys
597 print " System : %10.2f s." % t_sys
596 else:
598 else:
597 runs = range(nruns)
599 runs = range(nruns)
598 t0 = clock2()
600 t0 = clock2()
599 for nr in runs:
601 for nr in runs:
600 runner(filename, prog_ns, prog_ns,
602 runner(filename, prog_ns, prog_ns,
601 exit_ignore=exit_ignore)
603 exit_ignore=exit_ignore)
602 t1 = clock2()
604 t1 = clock2()
603 t_usr = t1[0] - t0[0]
605 t_usr = t1[0] - t0[0]
604 t_sys = t1[1] - t0[1]
606 t_sys = t1[1] - t0[1]
605 print "\nIPython CPU timings (estimated):"
607 print "\nIPython CPU timings (estimated):"
606 print "Total runs performed:", nruns
608 print "Total runs performed:", nruns
607 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
609 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
608 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
610 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
609 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
611 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
610 twall1 = time.time()
612 twall1 = time.time()
611 print "Wall time: %10.2f s." % (twall1 - twall0)
613 print "Wall time: %10.2f s." % (twall1 - twall0)
612
614
613 else:
615 else:
614 # regular execution
616 # regular execution
615 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
617 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
616
618
617 if 'i' in opts:
619 if 'i' in opts:
618 self.shell.user_ns['__name__'] = __name__save
620 self.shell.user_ns['__name__'] = __name__save
619 else:
621 else:
620 # The shell MUST hold a reference to prog_ns so after %run
622 # The shell MUST hold a reference to prog_ns so after %run
621 # exits, the python deletion mechanism doesn't zero it out
623 # exits, the python deletion mechanism doesn't zero it out
622 # (leaving dangling references).
624 # (leaving dangling references).
623 self.shell.cache_main_mod(prog_ns, filename)
625 self.shell.cache_main_mod(prog_ns, filename)
624 # update IPython interactive namespace
626 # update IPython interactive namespace
625
627
626 # Some forms of read errors on the file may mean the
628 # Some forms of read errors on the file may mean the
627 # __name__ key was never set; using pop we don't have to
629 # __name__ key was never set; using pop we don't have to
628 # worry about a possible KeyError.
630 # worry about a possible KeyError.
629 prog_ns.pop('__name__', None)
631 prog_ns.pop('__name__', None)
630
632
631 self.shell.user_ns.update(prog_ns)
633 self.shell.user_ns.update(prog_ns)
632 finally:
634 finally:
633 # It's a bit of a mystery why, but __builtins__ can change from
635 # It's a bit of a mystery why, but __builtins__ can change from
634 # being a module to becoming a dict missing some key data after
636 # being a module to becoming a dict missing some key data after
635 # %run. As best I can see, this is NOT something IPython is doing
637 # %run. As best I can see, this is NOT something IPython is doing
636 # at all, and similar problems have been reported before:
638 # at all, and similar problems have been reported before:
637 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
639 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
638 # Since this seems to be done by the interpreter itself, the best
640 # Since this seems to be done by the interpreter itself, the best
639 # we can do is to at least restore __builtins__ for the user on
641 # we can do is to at least restore __builtins__ for the user on
640 # exit.
642 # exit.
641 self.shell.user_ns['__builtins__'] = builtin_mod
643 self.shell.user_ns['__builtins__'] = builtin_mod
642
644
643 # Ensure key global structures are restored
645 # Ensure key global structures are restored
644 sys.argv = save_argv
646 sys.argv = save_argv
645 if restore_main:
647 if restore_main:
646 sys.modules['__main__'] = restore_main
648 sys.modules['__main__'] = restore_main
647 else:
649 else:
648 # Remove from sys.modules the reference to main_mod we'd
650 # Remove from sys.modules the reference to main_mod we'd
649 # added. Otherwise it will trap references to objects
651 # added. Otherwise it will trap references to objects
650 # contained therein.
652 # contained therein.
651 del sys.modules[main_mod_name]
653 del sys.modules[main_mod_name]
652
654
653 return stats
655 return stats
654
656
655 @skip_doctest
657 @skip_doctest
656 @line_cell_magic
658 @line_cell_magic
657 def timeit(self, line='', cell=None):
659 def timeit(self, line='', cell=None):
658 """Time execution of a Python statement or expression
660 """Time execution of a Python statement or expression
659
661
660 Usage, in line mode:
662 Usage, in line mode:
661 %timeit [-n<N> -r<R> [-t|-c]] statement
663 %timeit [-n<N> -r<R> [-t|-c]] statement
662 or in cell mode:
664 or in cell mode:
663 %%timeit [-n<N> -r<R> [-t|-c]] setup_code
665 %%timeit [-n<N> -r<R> [-t|-c]] setup_code
664 code
666 code
665 code...
667 code...
666
668
667 Time execution of a Python statement or expression using the timeit
669 Time execution of a Python statement or expression using the timeit
668 module. This function can be used both as a line and cell magic:
670 module. This function can be used both as a line and cell magic:
669
671
670 - In line mode you can time a single-line statement (though multiple
672 - In line mode you can time a single-line statement (though multiple
671 ones can be chained with using semicolons).
673 ones can be chained with using semicolons).
672
674
673 - In cell mode, the statement in the first line is used as setup code
675 - In cell mode, the statement in the first line is used as setup code
674 (executed but not timed) and the body of the cell is timed. The cell
676 (executed but not timed) and the body of the cell is timed. The cell
675 body has access to any variables created in the setup code.
677 body has access to any variables created in the setup code.
676
678
677 Options:
679 Options:
678 -n<N>: execute the given statement <N> times in a loop. If this value
680 -n<N>: execute the given statement <N> times in a loop. If this value
679 is not given, a fitting value is chosen.
681 is not given, a fitting value is chosen.
680
682
681 -r<R>: repeat the loop iteration <R> times and take the best result.
683 -r<R>: repeat the loop iteration <R> times and take the best result.
682 Default: 3
684 Default: 3
683
685
684 -t: use time.time to measure the time, which is the default on Unix.
686 -t: use time.time to measure the time, which is the default on Unix.
685 This function measures wall time.
687 This function measures wall time.
686
688
687 -c: use time.clock to measure the time, which is the default on
689 -c: use time.clock to measure the time, which is the default on
688 Windows and measures wall time. On Unix, resource.getrusage is used
690 Windows and measures wall time. On Unix, resource.getrusage is used
689 instead and returns the CPU user time.
691 instead and returns the CPU user time.
690
692
691 -p<P>: use a precision of <P> digits to display the timing result.
693 -p<P>: use a precision of <P> digits to display the timing result.
692 Default: 3
694 Default: 3
693
695
694
696
695 Examples
697 Examples
696 --------
698 --------
697 ::
699 ::
698
700
699 In [1]: %timeit pass
701 In [1]: %timeit pass
700 10000000 loops, best of 3: 53.3 ns per loop
702 10000000 loops, best of 3: 53.3 ns per loop
701
703
702 In [2]: u = None
704 In [2]: u = None
703
705
704 In [3]: %timeit u is None
706 In [3]: %timeit u is None
705 10000000 loops, best of 3: 184 ns per loop
707 10000000 loops, best of 3: 184 ns per loop
706
708
707 In [4]: %timeit -r 4 u == None
709 In [4]: %timeit -r 4 u == None
708 1000000 loops, best of 4: 242 ns per loop
710 1000000 loops, best of 4: 242 ns per loop
709
711
710 In [5]: import time
712 In [5]: import time
711
713
712 In [6]: %timeit -n1 time.sleep(2)
714 In [6]: %timeit -n1 time.sleep(2)
713 1 loops, best of 3: 2 s per loop
715 1 loops, best of 3: 2 s per loop
714
716
715
717
716 The times reported by %timeit will be slightly higher than those
718 The times reported by %timeit will be slightly higher than those
717 reported by the timeit.py script when variables are accessed. This is
719 reported by the timeit.py script when variables are accessed. This is
718 due to the fact that %timeit executes the statement in the namespace
720 due to the fact that %timeit executes the statement in the namespace
719 of the shell, compared with timeit.py, which uses a single setup
721 of the shell, compared with timeit.py, which uses a single setup
720 statement to import function or create variables. Generally, the bias
722 statement to import function or create variables. Generally, the bias
721 does not matter as long as results from timeit.py are not mixed with
723 does not matter as long as results from timeit.py are not mixed with
722 those from %timeit."""
724 those from %timeit."""
723
725
724 import timeit
726 import timeit
725 import math
727 import math
726
728
727 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
729 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
728 # certain terminals. Until we figure out a robust way of
730 # certain terminals. Until we figure out a robust way of
729 # auto-detecting if the terminal can deal with it, use plain 'us' for
731 # auto-detecting if the terminal can deal with it, use plain 'us' for
730 # microseconds. I am really NOT happy about disabling the proper
732 # microseconds. I am really NOT happy about disabling the proper
731 # 'micro' prefix, but crashing is worse... If anyone knows what the
733 # 'micro' prefix, but crashing is worse... If anyone knows what the
732 # right solution for this is, I'm all ears...
734 # right solution for this is, I'm all ears...
733 #
735 #
734 # Note: using
736 # Note: using
735 #
737 #
736 # s = u'\xb5'
738 # s = u'\xb5'
737 # s.encode(sys.getdefaultencoding())
739 # s.encode(sys.getdefaultencoding())
738 #
740 #
739 # is not sufficient, as I've seen terminals where that fails but
741 # is not sufficient, as I've seen terminals where that fails but
740 # print s
742 # print s
741 #
743 #
742 # succeeds
744 # succeeds
743 #
745 #
744 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
746 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
745
747
746 #units = [u"s", u"ms",u'\xb5',"ns"]
748 #units = [u"s", u"ms",u'\xb5',"ns"]
747 units = [u"s", u"ms",u'us',"ns"]
749 units = [u"s", u"ms",u'us',"ns"]
748
750
749 scaling = [1, 1e3, 1e6, 1e9]
751 scaling = [1, 1e3, 1e6, 1e9]
750
752
751 opts, stmt = self.parse_options(line,'n:r:tcp:',
753 opts, stmt = self.parse_options(line,'n:r:tcp:',
752 posix=False, strict=False)
754 posix=False, strict=False)
753 if stmt == "" and cell is None:
755 if stmt == "" and cell is None:
754 return
756 return
755 timefunc = timeit.default_timer
757 timefunc = timeit.default_timer
756 number = int(getattr(opts, "n", 0))
758 number = int(getattr(opts, "n", 0))
757 repeat = int(getattr(opts, "r", timeit.default_repeat))
759 repeat = int(getattr(opts, "r", timeit.default_repeat))
758 precision = int(getattr(opts, "p", 3))
760 precision = int(getattr(opts, "p", 3))
759 if hasattr(opts, "t"):
761 if hasattr(opts, "t"):
760 timefunc = time.time
762 timefunc = time.time
761 if hasattr(opts, "c"):
763 if hasattr(opts, "c"):
762 timefunc = clock
764 timefunc = clock
763
765
764 timer = timeit.Timer(timer=timefunc)
766 timer = timeit.Timer(timer=timefunc)
765 # this code has tight coupling to the inner workings of timeit.Timer,
767 # this code has tight coupling to the inner workings of timeit.Timer,
766 # but is there a better way to achieve that the code stmt has access
768 # but is there a better way to achieve that the code stmt has access
767 # to the shell namespace?
769 # to the shell namespace?
768
770
769 if cell is None:
771 if cell is None:
770 # called as line magic
772 # called as line magic
771 setup = 'pass'
773 setup = 'pass'
772 stmt = timeit.reindent(stmt, 8)
774 stmt = timeit.reindent(stmt, 8)
773 else:
775 else:
774 setup = timeit.reindent(stmt, 4)
776 setup = timeit.reindent(stmt, 4)
775 stmt = timeit.reindent(cell, 8)
777 stmt = timeit.reindent(cell, 8)
776
778
777 # From Python 3.3, this template uses new-style string formatting.
779 # From Python 3.3, this template uses new-style string formatting.
778 if sys.version_info >= (3, 3):
780 if sys.version_info >= (3, 3):
779 src = timeit.template.format(stmt=stmt, setup=setup)
781 src = timeit.template.format(stmt=stmt, setup=setup)
780 else:
782 else:
781 src = timeit.template % dict(stmt=stmt, setup=setup)
783 src = timeit.template % dict(stmt=stmt, setup=setup)
782
784
783 # Track compilation time so it can be reported if too long
785 # Track compilation time so it can be reported if too long
784 # Minimum time above which compilation time will be reported
786 # Minimum time above which compilation time will be reported
785 tc_min = 0.1
787 tc_min = 0.1
786
788
787 t0 = clock()
789 t0 = clock()
788 code = compile(src, "<magic-timeit>", "exec")
790 code = compile(src, "<magic-timeit>", "exec")
789 tc = clock()-t0
791 tc = clock()-t0
790
792
791 ns = {}
793 ns = {}
792 exec code in self.shell.user_ns, ns
794 exec code in self.shell.user_ns, ns
793 timer.inner = ns["inner"]
795 timer.inner = ns["inner"]
794
796
795 if number == 0:
797 if number == 0:
796 # determine number so that 0.2 <= total time < 2.0
798 # determine number so that 0.2 <= total time < 2.0
797 number = 1
799 number = 1
798 for i in range(1, 10):
800 for i in range(1, 10):
799 if timer.timeit(number) >= 0.2:
801 if timer.timeit(number) >= 0.2:
800 break
802 break
801 number *= 10
803 number *= 10
802
804
803 best = min(timer.repeat(repeat, number)) / number
805 best = min(timer.repeat(repeat, number)) / number
804
806
805 if best > 0.0 and best < 1000.0:
807 if best > 0.0 and best < 1000.0:
806 order = min(-int(math.floor(math.log10(best)) // 3), 3)
808 order = min(-int(math.floor(math.log10(best)) // 3), 3)
807 elif best >= 1000.0:
809 elif best >= 1000.0:
808 order = 0
810 order = 0
809 else:
811 else:
810 order = 3
812 order = 3
811 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
813 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
812 precision,
814 precision,
813 best * scaling[order],
815 best * scaling[order],
814 units[order])
816 units[order])
815 if tc > tc_min:
817 if tc > tc_min:
816 print "Compiler time: %.2f s" % tc
818 print "Compiler time: %.2f s" % tc
817
819
818 @skip_doctest
820 @skip_doctest
819 @needs_local_scope
821 @needs_local_scope
820 @line_magic
822 @line_magic
821 def time(self,parameter_s, user_locals):
823 def time(self,parameter_s, user_locals):
822 """Time execution of a Python statement or expression.
824 """Time execution of a Python statement or expression.
823
825
824 The CPU and wall clock times are printed, and the value of the
826 The CPU and wall clock times are printed, and the value of the
825 expression (if any) is returned. Note that under Win32, system time
827 expression (if any) is returned. Note that under Win32, system time
826 is always reported as 0, since it can not be measured.
828 is always reported as 0, since it can not be measured.
827
829
828 This function provides very basic timing functionality. In Python
830 This function provides very basic timing functionality. In Python
829 2.3, the timeit module offers more control and sophistication, so this
831 2.3, the timeit module offers more control and sophistication, so this
830 could be rewritten to use it (patches welcome).
832 could be rewritten to use it (patches welcome).
831
833
832 Examples
834 Examples
833 --------
835 --------
834 ::
836 ::
835
837
836 In [1]: time 2**128
838 In [1]: time 2**128
837 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
839 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
838 Wall time: 0.00
840 Wall time: 0.00
839 Out[1]: 340282366920938463463374607431768211456L
841 Out[1]: 340282366920938463463374607431768211456L
840
842
841 In [2]: n = 1000000
843 In [2]: n = 1000000
842
844
843 In [3]: time sum(range(n))
845 In [3]: time sum(range(n))
844 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
846 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
845 Wall time: 1.37
847 Wall time: 1.37
846 Out[3]: 499999500000L
848 Out[3]: 499999500000L
847
849
848 In [4]: time print 'hello world'
850 In [4]: time print 'hello world'
849 hello world
851 hello world
850 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
852 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
851 Wall time: 0.00
853 Wall time: 0.00
852
854
853 Note that the time needed by Python to compile the given expression
855 Note that the time needed by Python to compile the given expression
854 will be reported if it is more than 0.1s. In this example, the
856 will be reported if it is more than 0.1s. In this example, the
855 actual exponentiation is done by Python at compilation time, so while
857 actual exponentiation is done by Python at compilation time, so while
856 the expression can take a noticeable amount of time to compute, that
858 the expression can take a noticeable amount of time to compute, that
857 time is purely due to the compilation:
859 time is purely due to the compilation:
858
860
859 In [5]: time 3**9999;
861 In [5]: time 3**9999;
860 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
862 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
861 Wall time: 0.00 s
863 Wall time: 0.00 s
862
864
863 In [6]: time 3**999999;
865 In [6]: time 3**999999;
864 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
866 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
865 Wall time: 0.00 s
867 Wall time: 0.00 s
866 Compiler : 0.78 s
868 Compiler : 0.78 s
867 """
869 """
868
870
869 # fail immediately if the given expression can't be compiled
871 # fail immediately if the given expression can't be compiled
870
872
871 expr = self.shell.prefilter(parameter_s,False)
873 expr = self.shell.prefilter(parameter_s,False)
872
874
873 # Minimum time above which compilation time will be reported
875 # Minimum time above which compilation time will be reported
874 tc_min = 0.1
876 tc_min = 0.1
875
877
876 try:
878 try:
877 mode = 'eval'
879 mode = 'eval'
878 t0 = clock()
880 t0 = clock()
879 code = compile(expr,'<timed eval>',mode)
881 code = compile(expr,'<timed eval>',mode)
880 tc = clock()-t0
882 tc = clock()-t0
881 except SyntaxError:
883 except SyntaxError:
882 mode = 'exec'
884 mode = 'exec'
883 t0 = clock()
885 t0 = clock()
884 code = compile(expr,'<timed exec>',mode)
886 code = compile(expr,'<timed exec>',mode)
885 tc = clock()-t0
887 tc = clock()-t0
886 # skew measurement as little as possible
888 # skew measurement as little as possible
887 glob = self.shell.user_ns
889 glob = self.shell.user_ns
888 wtime = time.time
890 wtime = time.time
889 # time execution
891 # time execution
890 wall_st = wtime()
892 wall_st = wtime()
891 if mode=='eval':
893 if mode=='eval':
892 st = clock2()
894 st = clock2()
893 out = eval(code, glob, user_locals)
895 out = eval(code, glob, user_locals)
894 end = clock2()
896 end = clock2()
895 else:
897 else:
896 st = clock2()
898 st = clock2()
897 exec code in glob, user_locals
899 exec code in glob, user_locals
898 end = clock2()
900 end = clock2()
899 out = None
901 out = None
900 wall_end = wtime()
902 wall_end = wtime()
901 # Compute actual times and report
903 # Compute actual times and report
902 wall_time = wall_end-wall_st
904 wall_time = wall_end-wall_st
903 cpu_user = end[0]-st[0]
905 cpu_user = end[0]-st[0]
904 cpu_sys = end[1]-st[1]
906 cpu_sys = end[1]-st[1]
905 cpu_tot = cpu_user+cpu_sys
907 cpu_tot = cpu_user+cpu_sys
906 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
908 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
907 (cpu_user,cpu_sys,cpu_tot)
909 (cpu_user,cpu_sys,cpu_tot)
908 print "Wall time: %.2f s" % wall_time
910 print "Wall time: %.2f s" % wall_time
909 if tc > tc_min:
911 if tc > tc_min:
910 print "Compiler : %.2f s" % tc
912 print "Compiler : %.2f s" % tc
911 return out
913 return out
912
914
913 @skip_doctest
915 @skip_doctest
914 @line_magic
916 @line_magic
915 def macro(self, parameter_s=''):
917 def macro(self, parameter_s=''):
916 """Define a macro for future re-execution. It accepts ranges of history,
918 """Define a macro for future re-execution. It accepts ranges of history,
917 filenames or string objects.
919 filenames or string objects.
918
920
919 Usage:\\
921 Usage:\\
920 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
922 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
921
923
922 Options:
924 Options:
923
925
924 -r: use 'raw' input. By default, the 'processed' history is used,
926 -r: use 'raw' input. By default, the 'processed' history is used,
925 so that magics are loaded in their transformed version to valid
927 so that magics are loaded in their transformed version to valid
926 Python. If this option is given, the raw input as typed as the
928 Python. If this option is given, the raw input as typed as the
927 command line is used instead.
929 command line is used instead.
928
930
929 This will define a global variable called `name` which is a string
931 This will define a global variable called `name` which is a string
930 made of joining the slices and lines you specify (n1,n2,... numbers
932 made of joining the slices and lines you specify (n1,n2,... numbers
931 above) from your input history into a single string. This variable
933 above) from your input history into a single string. This variable
932 acts like an automatic function which re-executes those lines as if
934 acts like an automatic function which re-executes those lines as if
933 you had typed them. You just type 'name' at the prompt and the code
935 you had typed them. You just type 'name' at the prompt and the code
934 executes.
936 executes.
935
937
936 The syntax for indicating input ranges is described in %history.
938 The syntax for indicating input ranges is described in %history.
937
939
938 Note: as a 'hidden' feature, you can also use traditional python slice
940 Note: as a 'hidden' feature, you can also use traditional python slice
939 notation, where N:M means numbers N through M-1.
941 notation, where N:M means numbers N through M-1.
940
942
941 For example, if your history contains (%hist prints it)::
943 For example, if your history contains (%hist prints it)::
942
944
943 44: x=1
945 44: x=1
944 45: y=3
946 45: y=3
945 46: z=x+y
947 46: z=x+y
946 47: print x
948 47: print x
947 48: a=5
949 48: a=5
948 49: print 'x',x,'y',y
950 49: print 'x',x,'y',y
949
951
950 you can create a macro with lines 44 through 47 (included) and line 49
952 you can create a macro with lines 44 through 47 (included) and line 49
951 called my_macro with::
953 called my_macro with::
952
954
953 In [55]: %macro my_macro 44-47 49
955 In [55]: %macro my_macro 44-47 49
954
956
955 Now, typing `my_macro` (without quotes) will re-execute all this code
957 Now, typing `my_macro` (without quotes) will re-execute all this code
956 in one pass.
958 in one pass.
957
959
958 You don't need to give the line-numbers in order, and any given line
960 You don't need to give the line-numbers in order, and any given line
959 number can appear multiple times. You can assemble macros with any
961 number can appear multiple times. You can assemble macros with any
960 lines from your input history in any order.
962 lines from your input history in any order.
961
963
962 The macro is a simple object which holds its value in an attribute,
964 The macro is a simple object which holds its value in an attribute,
963 but IPython's display system checks for macros and executes them as
965 but IPython's display system checks for macros and executes them as
964 code instead of printing them when you type their name.
966 code instead of printing them when you type their name.
965
967
966 You can view a macro's contents by explicitly printing it with::
968 You can view a macro's contents by explicitly printing it with::
967
969
968 print macro_name
970 print macro_name
969
971
970 """
972 """
971 opts,args = self.parse_options(parameter_s,'r',mode='list')
973 opts,args = self.parse_options(parameter_s,'r',mode='list')
972 if not args: # List existing macros
974 if not args: # List existing macros
973 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
975 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
974 isinstance(v, Macro))
976 isinstance(v, Macro))
975 if len(args) == 1:
977 if len(args) == 1:
976 raise UsageError(
978 raise UsageError(
977 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
979 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
978 name, codefrom = args[0], " ".join(args[1:])
980 name, codefrom = args[0], " ".join(args[1:])
979
981
980 #print 'rng',ranges # dbg
982 #print 'rng',ranges # dbg
981 try:
983 try:
982 lines = self.shell.find_user_code(codefrom, 'r' in opts)
984 lines = self.shell.find_user_code(codefrom, 'r' in opts)
983 except (ValueError, TypeError) as e:
985 except (ValueError, TypeError) as e:
984 print e.args[0]
986 print e.args[0]
985 return
987 return
986 macro = Macro(lines)
988 macro = Macro(lines)
987 self.shell.define_macro(name, macro)
989 self.shell.define_macro(name, macro)
988 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
990 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
989 print '=== Macro contents: ==='
991 print '=== Macro contents: ==='
990 print macro,
992 print macro,
993
994 @magic_arguments.magic_arguments()
995 @magic_arguments.argument('-o', '--out', type=str,
996 help="""The name of the variable in which to store stdout
997
998 If unspecified: stdout is discarded
999 """
1000 )
1001 @magic_arguments.argument('-e', '--err', type=str,
1002 help="""The name of the variable in which to store stderr
1003
1004 If unspecified: stderr is discarded
1005 """
1006 )
1007 @cell_magic
1008 def capture(self, line, cell):
1009 """run the cell, capturing stdout/err"""
1010 args = magic_arguments.parse_argstring(self.capture, line)
1011 with capture_output() as io:
1012 self.shell.run_cell(cell)
1013 if args.out:
1014 self.shell.user_ns[args.out] = io.stdout
1015 if args.err:
1016 self.shell.user_ns[args.err] = io.stderr
General Comments 0
You need to be logged in to leave comments. Login now