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