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