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