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