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