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