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