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