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