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