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