##// END OF EJS Templates
Remove debugger curframe attribute before using checkline()...
Thomas Kluyver -
Show More
@@ -1,1368 +1,1373 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
820 # handle it not existing. https://github.com/ipython/ipython/issues/10028
821 if hasattr(deb, 'curframe'):
822 del deb.curframe
823
819 # reset Breakpoint state, which is moronically kept
824 # reset Breakpoint state, which is moronically kept
820 # in a class
825 # in a class
821 bdb.Breakpoint.next = 1
826 bdb.Breakpoint.next = 1
822 bdb.Breakpoint.bplist = {}
827 bdb.Breakpoint.bplist = {}
823 bdb.Breakpoint.bpbynumber = [None]
828 bdb.Breakpoint.bpbynumber = [None]
824 if bp_line is not None:
829 if bp_line is not None:
825 # Set an initial breakpoint to stop execution
830 # Set an initial breakpoint to stop execution
826 maxtries = 10
831 maxtries = 10
827 bp_file = bp_file or filename
832 bp_file = bp_file or filename
828 checkline = deb.checkline(bp_file, bp_line)
833 checkline = deb.checkline(bp_file, bp_line)
829 if not checkline:
834 if not checkline:
830 for bp in range(bp_line + 1, bp_line + maxtries + 1):
835 for bp in range(bp_line + 1, bp_line + maxtries + 1):
831 if deb.checkline(bp_file, bp):
836 if deb.checkline(bp_file, bp):
832 break
837 break
833 else:
838 else:
834 msg = ("\nI failed to find a valid line to set "
839 msg = ("\nI failed to find a valid line to set "
835 "a breakpoint\n"
840 "a breakpoint\n"
836 "after trying up to line: %s.\n"
841 "after trying up to line: %s.\n"
837 "Please set a valid breakpoint manually "
842 "Please set a valid breakpoint manually "
838 "with the -b option." % bp)
843 "with the -b option." % bp)
839 raise UsageError(msg)
844 raise UsageError(msg)
840 # if we find a good linenumber, set the breakpoint
845 # if we find a good linenumber, set the breakpoint
841 deb.do_break('%s:%s' % (bp_file, bp_line))
846 deb.do_break('%s:%s' % (bp_file, bp_line))
842
847
843 if filename:
848 if filename:
844 # Mimic Pdb._runscript(...)
849 # Mimic Pdb._runscript(...)
845 deb._wait_for_mainpyfile = True
850 deb._wait_for_mainpyfile = True
846 deb.mainpyfile = deb.canonic(filename)
851 deb.mainpyfile = deb.canonic(filename)
847
852
848 # Start file run
853 # Start file run
849 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)
850 try:
855 try:
851 if filename:
856 if filename:
852 # 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
853 deb._exec_filename = filename
858 deb._exec_filename = filename
854 while True:
859 while True:
855 try:
860 try:
856 deb.run(code, code_ns)
861 deb.run(code, code_ns)
857 except Restart:
862 except Restart:
858 print("Restarting")
863 print("Restarting")
859 if filename:
864 if filename:
860 deb._wait_for_mainpyfile = True
865 deb._wait_for_mainpyfile = True
861 deb.mainpyfile = deb.canonic(filename)
866 deb.mainpyfile = deb.canonic(filename)
862 continue
867 continue
863 else:
868 else:
864 break
869 break
865
870
866
871
867 except:
872 except:
868 etype, value, tb = sys.exc_info()
873 etype, value, tb = sys.exc_info()
869 # Skip three frames in the traceback: the %run one,
874 # Skip three frames in the traceback: the %run one,
870 # one inside bdb.py, and the command-line typed by the
875 # one inside bdb.py, and the command-line typed by the
871 # user (run by exec in pdb itself).
876 # user (run by exec in pdb itself).
872 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
877 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
873
878
874 @staticmethod
879 @staticmethod
875 def _run_with_timing(run, nruns):
880 def _run_with_timing(run, nruns):
876 """
881 """
877 Run function `run` and print timing information.
882 Run function `run` and print timing information.
878
883
879 Parameters
884 Parameters
880 ----------
885 ----------
881 run : callable
886 run : callable
882 Any callable object which takes no argument.
887 Any callable object which takes no argument.
883 nruns : int
888 nruns : int
884 Number of times to execute `run`.
889 Number of times to execute `run`.
885
890
886 """
891 """
887 twall0 = time.time()
892 twall0 = time.time()
888 if nruns == 1:
893 if nruns == 1:
889 t0 = clock2()
894 t0 = clock2()
890 run()
895 run()
891 t1 = clock2()
896 t1 = clock2()
892 t_usr = t1[0] - t0[0]
897 t_usr = t1[0] - t0[0]
893 t_sys = t1[1] - t0[1]
898 t_sys = t1[1] - t0[1]
894 print("\nIPython CPU timings (estimated):")
899 print("\nIPython CPU timings (estimated):")
895 print(" User : %10.2f s." % t_usr)
900 print(" User : %10.2f s." % t_usr)
896 print(" System : %10.2f s." % t_sys)
901 print(" System : %10.2f s." % t_sys)
897 else:
902 else:
898 runs = range(nruns)
903 runs = range(nruns)
899 t0 = clock2()
904 t0 = clock2()
900 for nr in runs:
905 for nr in runs:
901 run()
906 run()
902 t1 = clock2()
907 t1 = clock2()
903 t_usr = t1[0] - t0[0]
908 t_usr = t1[0] - t0[0]
904 t_sys = t1[1] - t0[1]
909 t_sys = t1[1] - t0[1]
905 print("\nIPython CPU timings (estimated):")
910 print("\nIPython CPU timings (estimated):")
906 print("Total runs performed:", nruns)
911 print("Total runs performed:", nruns)
907 print(" Times : %10s %10s" % ('Total', 'Per run'))
912 print(" Times : %10s %10s" % ('Total', 'Per run'))
908 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))
909 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))
910 twall1 = time.time()
915 twall1 = time.time()
911 print("Wall time: %10.2f s." % (twall1 - twall0))
916 print("Wall time: %10.2f s." % (twall1 - twall0))
912
917
913 @skip_doctest
918 @skip_doctest
914 @line_cell_magic
919 @line_cell_magic
915 def timeit(self, line='', cell=None):
920 def timeit(self, line='', cell=None):
916 """Time execution of a Python statement or expression
921 """Time execution of a Python statement or expression
917
922
918 Usage, in line mode:
923 Usage, in line mode:
919 %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
920 or in cell mode:
925 or in cell mode:
921 %%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
922 code
927 code
923 code...
928 code...
924
929
925 Time execution of a Python statement or expression using the timeit
930 Time execution of a Python statement or expression using the timeit
926 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:
927
932
928 - 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
929 ones can be chained with using semicolons).
934 ones can be chained with using semicolons).
930
935
931 - 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
932 (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
933 body has access to any variables created in the setup code.
938 body has access to any variables created in the setup code.
934
939
935 Options:
940 Options:
936 -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
937 is not given, a fitting value is chosen.
942 is not given, a fitting value is chosen.
938
943
939 -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.
940 Default: 3
945 Default: 3
941
946
942 -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.
943 This function measures wall time.
948 This function measures wall time.
944
949
945 -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
946 Windows and measures wall time. On Unix, resource.getrusage is used
951 Windows and measures wall time. On Unix, resource.getrusage is used
947 instead and returns the CPU user time.
952 instead and returns the CPU user time.
948
953
949 -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.
950 Default: 3
955 Default: 3
951
956
952 -q: Quiet, do not print result.
957 -q: Quiet, do not print result.
953
958
954 -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
955 the result in more details.
960 the result in more details.
956
961
957
962
958 Examples
963 Examples
959 --------
964 --------
960 ::
965 ::
961
966
962 In [1]: %timeit pass
967 In [1]: %timeit pass
963 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)
964
969
965 In [2]: u = None
970 In [2]: u = None
966
971
967 In [3]: %timeit u is None
972 In [3]: %timeit u is None
968 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)
969
974
970 In [4]: %timeit -r 4 u == None
975 In [4]: %timeit -r 4 u == None
971 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)
972
977
973 In [5]: import time
978 In [5]: import time
974
979
975 In [6]: %timeit -n1 time.sleep(2)
980 In [6]: %timeit -n1 time.sleep(2)
976 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)
977
982
978
983
979 The times reported by %timeit will be slightly higher than those
984 The times reported by %timeit will be slightly higher than those
980 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
981 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
982 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
983 statement to import function or create variables. Generally, the bias
988 statement to import function or create variables. Generally, the bias
984 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
985 those from %timeit."""
990 those from %timeit."""
986
991
987 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
992 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
988 posix=False, strict=False)
993 posix=False, strict=False)
989 if stmt == "" and cell is None:
994 if stmt == "" and cell is None:
990 return
995 return
991
996
992 timefunc = timeit.default_timer
997 timefunc = timeit.default_timer
993 number = int(getattr(opts, "n", 0))
998 number = int(getattr(opts, "n", 0))
994 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
995 repeat = int(getattr(opts, "r", default_repeat))
1000 repeat = int(getattr(opts, "r", default_repeat))
996 precision = int(getattr(opts, "p", 3))
1001 precision = int(getattr(opts, "p", 3))
997 quiet = 'q' in opts
1002 quiet = 'q' in opts
998 return_result = 'o' in opts
1003 return_result = 'o' in opts
999 if hasattr(opts, "t"):
1004 if hasattr(opts, "t"):
1000 timefunc = time.time
1005 timefunc = time.time
1001 if hasattr(opts, "c"):
1006 if hasattr(opts, "c"):
1002 timefunc = clock
1007 timefunc = clock
1003
1008
1004 timer = Timer(timer=timefunc)
1009 timer = Timer(timer=timefunc)
1005 # 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,
1006 # 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
1007 # to the shell namespace?
1012 # to the shell namespace?
1008 transform = self.shell.input_splitter.transform_cell
1013 transform = self.shell.input_splitter.transform_cell
1009
1014
1010 if cell is None:
1015 if cell is None:
1011 # called as line magic
1016 # called as line magic
1012 ast_setup = self.shell.compile.ast_parse("pass")
1017 ast_setup = self.shell.compile.ast_parse("pass")
1013 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1018 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1014 else:
1019 else:
1015 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1020 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1016 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1021 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1017
1022
1018 ast_setup = self.shell.transform_ast(ast_setup)
1023 ast_setup = self.shell.transform_ast(ast_setup)
1019 ast_stmt = self.shell.transform_ast(ast_stmt)
1024 ast_stmt = self.shell.transform_ast(ast_stmt)
1020
1025
1021 # 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
1022 # 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
1023 # without affecting the timing code.
1028 # without affecting the timing code.
1024 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1029 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1025 ' setup\n'
1030 ' setup\n'
1026 ' _t0 = _timer()\n'
1031 ' _t0 = _timer()\n'
1027 ' for _i in _it:\n'
1032 ' for _i in _it:\n'
1028 ' stmt\n'
1033 ' stmt\n'
1029 ' _t1 = _timer()\n'
1034 ' _t1 = _timer()\n'
1030 ' return _t1 - _t0\n')
1035 ' return _t1 - _t0\n')
1031
1036
1032 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1037 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1033 timeit_ast = ast.fix_missing_locations(timeit_ast)
1038 timeit_ast = ast.fix_missing_locations(timeit_ast)
1034
1039
1035 # Track compilation time so it can be reported if too long
1040 # Track compilation time so it can be reported if too long
1036 # Minimum time above which compilation time will be reported
1041 # Minimum time above which compilation time will be reported
1037 tc_min = 0.1
1042 tc_min = 0.1
1038
1043
1039 t0 = clock()
1044 t0 = clock()
1040 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1045 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1041 tc = clock()-t0
1046 tc = clock()-t0
1042
1047
1043 ns = {}
1048 ns = {}
1044 exec(code, self.shell.user_ns, ns)
1049 exec(code, self.shell.user_ns, ns)
1045 timer.inner = ns["inner"]
1050 timer.inner = ns["inner"]
1046
1051
1047 # 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
1048 # best and worst timings.
1053 # best and worst timings.
1049 # Issue: https://github.com/ipython/ipython/issues/6471
1054 # Issue: https://github.com/ipython/ipython/issues/6471
1050 if number == 0:
1055 if number == 0:
1051 # determine number so that 0.2 <= total time < 2.0
1056 # determine number so that 0.2 <= total time < 2.0
1052 for index in range(0, 10):
1057 for index in range(0, 10):
1053 number = 10 ** index
1058 number = 10 ** index
1054 time_number = timer.timeit(number)
1059 time_number = timer.timeit(number)
1055 if time_number >= 0.2:
1060 if time_number >= 0.2:
1056 break
1061 break
1057
1062
1058 all_runs = timer.repeat(repeat, number)
1063 all_runs = timer.repeat(repeat, number)
1059 best = min(all_runs) / number
1064 best = min(all_runs) / number
1060 worst = max(all_runs) / number
1065 worst = max(all_runs) / number
1061 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1066 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1062
1067
1063 if not quiet :
1068 if not quiet :
1064 # Check best timing is greater than zero to avoid a
1069 # Check best timing is greater than zero to avoid a
1065 # ZeroDivisionError.
1070 # ZeroDivisionError.
1066 # In cases where the slowest timing is lesser than a micosecond
1071 # In cases where the slowest timing is lesser than a micosecond
1067 # we assume that it does not really matter if the fastest
1072 # we assume that it does not really matter if the fastest
1068 # timing is 4 times faster than the slowest timing or not.
1073 # timing is 4 times faster than the slowest timing or not.
1069 if worst > 4 * best and best > 0 and worst > 1e-6:
1074 if worst > 4 * best and best > 0 and worst > 1e-6:
1070 print("The slowest run took %0.2f times longer than the "
1075 print("The slowest run took %0.2f times longer than the "
1071 "fastest. This could mean that an intermediate result "
1076 "fastest. This could mean that an intermediate result "
1072 "is being cached." % (worst / best))
1077 "is being cached." % (worst / best))
1073
1078
1074 print( timeit_result )
1079 print( timeit_result )
1075
1080
1076 if tc > tc_min:
1081 if tc > tc_min:
1077 print("Compiler time: %.2f s" % tc)
1082 print("Compiler time: %.2f s" % tc)
1078 if return_result:
1083 if return_result:
1079 return timeit_result
1084 return timeit_result
1080
1085
1081 @skip_doctest
1086 @skip_doctest
1082 @needs_local_scope
1087 @needs_local_scope
1083 @line_cell_magic
1088 @line_cell_magic
1084 def time(self,line='', cell=None, local_ns=None):
1089 def time(self,line='', cell=None, local_ns=None):
1085 """Time execution of a Python statement or expression.
1090 """Time execution of a Python statement or expression.
1086
1091
1087 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
1088 expression (if any) is returned. Note that under Win32, system time
1093 expression (if any) is returned. Note that under Win32, system time
1089 is always reported as 0, since it can not be measured.
1094 is always reported as 0, since it can not be measured.
1090
1095
1091 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:
1092
1097
1093 - 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
1094 ones can be chained with using semicolons).
1099 ones can be chained with using semicolons).
1095
1100
1096 - In cell mode, you can time the cell body (a directly
1101 - In cell mode, you can time the cell body (a directly
1097 following statement raises an error).
1102 following statement raises an error).
1098
1103
1099 This function provides very basic timing functionality. Use the timeit
1104 This function provides very basic timing functionality. Use the timeit
1100 magic for more control over the measurement.
1105 magic for more control over the measurement.
1101
1106
1102 Examples
1107 Examples
1103 --------
1108 --------
1104 ::
1109 ::
1105
1110
1106 In [1]: %time 2**128
1111 In [1]: %time 2**128
1107 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
1108 Wall time: 0.00
1113 Wall time: 0.00
1109 Out[1]: 340282366920938463463374607431768211456L
1114 Out[1]: 340282366920938463463374607431768211456L
1110
1115
1111 In [2]: n = 1000000
1116 In [2]: n = 1000000
1112
1117
1113 In [3]: %time sum(range(n))
1118 In [3]: %time sum(range(n))
1114 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
1115 Wall time: 1.37
1120 Wall time: 1.37
1116 Out[3]: 499999500000L
1121 Out[3]: 499999500000L
1117
1122
1118 In [4]: %time print 'hello world'
1123 In [4]: %time print 'hello world'
1119 hello world
1124 hello world
1120 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
1121 Wall time: 0.00
1126 Wall time: 0.00
1122
1127
1123 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
1124 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
1125 actual exponentiation is done by Python at compilation time, so while
1130 actual exponentiation is done by Python at compilation time, so while
1126 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
1127 time is purely due to the compilation:
1132 time is purely due to the compilation:
1128
1133
1129 In [5]: %time 3**9999;
1134 In [5]: %time 3**9999;
1130 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
1131 Wall time: 0.00 s
1136 Wall time: 0.00 s
1132
1137
1133 In [6]: %time 3**999999;
1138 In [6]: %time 3**999999;
1134 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
1135 Wall time: 0.00 s
1140 Wall time: 0.00 s
1136 Compiler : 0.78 s
1141 Compiler : 0.78 s
1137 """
1142 """
1138
1143
1139 # fail immediately if the given expression can't be compiled
1144 # fail immediately if the given expression can't be compiled
1140
1145
1141 if line and cell:
1146 if line and cell:
1142 raise UsageError("Can't use statement directly after '%%time'!")
1147 raise UsageError("Can't use statement directly after '%%time'!")
1143
1148
1144 if cell:
1149 if cell:
1145 expr = self.shell.input_transformer_manager.transform_cell(cell)
1150 expr = self.shell.input_transformer_manager.transform_cell(cell)
1146 else:
1151 else:
1147 expr = self.shell.input_transformer_manager.transform_cell(line)
1152 expr = self.shell.input_transformer_manager.transform_cell(line)
1148
1153
1149 # Minimum time above which parse time will be reported
1154 # Minimum time above which parse time will be reported
1150 tp_min = 0.1
1155 tp_min = 0.1
1151
1156
1152 t0 = clock()
1157 t0 = clock()
1153 expr_ast = self.shell.compile.ast_parse(expr)
1158 expr_ast = self.shell.compile.ast_parse(expr)
1154 tp = clock()-t0
1159 tp = clock()-t0
1155
1160
1156 # Apply AST transformations
1161 # Apply AST transformations
1157 expr_ast = self.shell.transform_ast(expr_ast)
1162 expr_ast = self.shell.transform_ast(expr_ast)
1158
1163
1159 # Minimum time above which compilation time will be reported
1164 # Minimum time above which compilation time will be reported
1160 tc_min = 0.1
1165 tc_min = 0.1
1161
1166
1162 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):
1163 mode = 'eval'
1168 mode = 'eval'
1164 source = '<timed eval>'
1169 source = '<timed eval>'
1165 expr_ast = ast.Expression(expr_ast.body[0].value)
1170 expr_ast = ast.Expression(expr_ast.body[0].value)
1166 else:
1171 else:
1167 mode = 'exec'
1172 mode = 'exec'
1168 source = '<timed exec>'
1173 source = '<timed exec>'
1169 t0 = clock()
1174 t0 = clock()
1170 code = self.shell.compile(expr_ast, source, mode)
1175 code = self.shell.compile(expr_ast, source, mode)
1171 tc = clock()-t0
1176 tc = clock()-t0
1172
1177
1173 # skew measurement as little as possible
1178 # skew measurement as little as possible
1174 glob = self.shell.user_ns
1179 glob = self.shell.user_ns
1175 wtime = time.time
1180 wtime = time.time
1176 # time execution
1181 # time execution
1177 wall_st = wtime()
1182 wall_st = wtime()
1178 if mode=='eval':
1183 if mode=='eval':
1179 st = clock2()
1184 st = clock2()
1180 out = eval(code, glob, local_ns)
1185 out = eval(code, glob, local_ns)
1181 end = clock2()
1186 end = clock2()
1182 else:
1187 else:
1183 st = clock2()
1188 st = clock2()
1184 exec(code, glob, local_ns)
1189 exec(code, glob, local_ns)
1185 end = clock2()
1190 end = clock2()
1186 out = None
1191 out = None
1187 wall_end = wtime()
1192 wall_end = wtime()
1188 # Compute actual times and report
1193 # Compute actual times and report
1189 wall_time = wall_end-wall_st
1194 wall_time = wall_end-wall_st
1190 cpu_user = end[0]-st[0]
1195 cpu_user = end[0]-st[0]
1191 cpu_sys = end[1]-st[1]
1196 cpu_sys = end[1]-st[1]
1192 cpu_tot = cpu_user+cpu_sys
1197 cpu_tot = cpu_user+cpu_sys
1193 # On windows cpu_sys is always zero, so no new information to the next print
1198 # On windows cpu_sys is always zero, so no new information to the next print
1194 if sys.platform != 'win32':
1199 if sys.platform != 'win32':
1195 print("CPU times: user %s, sys: %s, total: %s" % \
1200 print("CPU times: user %s, sys: %s, total: %s" % \
1196 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1201 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1197 print("Wall time: %s" % _format_time(wall_time))
1202 print("Wall time: %s" % _format_time(wall_time))
1198 if tc > tc_min:
1203 if tc > tc_min:
1199 print("Compiler : %s" % _format_time(tc))
1204 print("Compiler : %s" % _format_time(tc))
1200 if tp > tp_min:
1205 if tp > tp_min:
1201 print("Parser : %s" % _format_time(tp))
1206 print("Parser : %s" % _format_time(tp))
1202 return out
1207 return out
1203
1208
1204 @skip_doctest
1209 @skip_doctest
1205 @line_magic
1210 @line_magic
1206 def macro(self, parameter_s=''):
1211 def macro(self, parameter_s=''):
1207 """Define a macro for future re-execution. It accepts ranges of history,
1212 """Define a macro for future re-execution. It accepts ranges of history,
1208 filenames or string objects.
1213 filenames or string objects.
1209
1214
1210 Usage:\\
1215 Usage:\\
1211 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1216 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1212
1217
1213 Options:
1218 Options:
1214
1219
1215 -r: use 'raw' input. By default, the 'processed' history is used,
1220 -r: use 'raw' input. By default, the 'processed' history is used,
1216 so that magics are loaded in their transformed version to valid
1221 so that magics are loaded in their transformed version to valid
1217 Python. If this option is given, the raw input as typed at the
1222 Python. If this option is given, the raw input as typed at the
1218 command line is used instead.
1223 command line is used instead.
1219
1224
1220 -q: quiet macro definition. By default, a tag line is printed
1225 -q: quiet macro definition. By default, a tag line is printed
1221 to indicate the macro has been created, and then the contents of
1226 to indicate the macro has been created, and then the contents of
1222 the macro are printed. If this option is given, then no printout
1227 the macro are printed. If this option is given, then no printout
1223 is produced once the macro is created.
1228 is produced once the macro is created.
1224
1229
1225 This will define a global variable called `name` which is a string
1230 This will define a global variable called `name` which is a string
1226 made of joining the slices and lines you specify (n1,n2,... numbers
1231 made of joining the slices and lines you specify (n1,n2,... numbers
1227 above) from your input history into a single string. This variable
1232 above) from your input history into a single string. This variable
1228 acts like an automatic function which re-executes those lines as if
1233 acts like an automatic function which re-executes those lines as if
1229 you had typed them. You just type 'name' at the prompt and the code
1234 you had typed them. You just type 'name' at the prompt and the code
1230 executes.
1235 executes.
1231
1236
1232 The syntax for indicating input ranges is described in %history.
1237 The syntax for indicating input ranges is described in %history.
1233
1238
1234 Note: as a 'hidden' feature, you can also use traditional python slice
1239 Note: as a 'hidden' feature, you can also use traditional python slice
1235 notation, where N:M means numbers N through M-1.
1240 notation, where N:M means numbers N through M-1.
1236
1241
1237 For example, if your history contains (print using %hist -n )::
1242 For example, if your history contains (print using %hist -n )::
1238
1243
1239 44: x=1
1244 44: x=1
1240 45: y=3
1245 45: y=3
1241 46: z=x+y
1246 46: z=x+y
1242 47: print x
1247 47: print x
1243 48: a=5
1248 48: a=5
1244 49: print 'x',x,'y',y
1249 49: print 'x',x,'y',y
1245
1250
1246 you can create a macro with lines 44 through 47 (included) and line 49
1251 you can create a macro with lines 44 through 47 (included) and line 49
1247 called my_macro with::
1252 called my_macro with::
1248
1253
1249 In [55]: %macro my_macro 44-47 49
1254 In [55]: %macro my_macro 44-47 49
1250
1255
1251 Now, typing `my_macro` (without quotes) will re-execute all this code
1256 Now, typing `my_macro` (without quotes) will re-execute all this code
1252 in one pass.
1257 in one pass.
1253
1258
1254 You don't need to give the line-numbers in order, and any given line
1259 You don't need to give the line-numbers in order, and any given line
1255 number can appear multiple times. You can assemble macros with any
1260 number can appear multiple times. You can assemble macros with any
1256 lines from your input history in any order.
1261 lines from your input history in any order.
1257
1262
1258 The macro is a simple object which holds its value in an attribute,
1263 The macro is a simple object which holds its value in an attribute,
1259 but IPython's display system checks for macros and executes them as
1264 but IPython's display system checks for macros and executes them as
1260 code instead of printing them when you type their name.
1265 code instead of printing them when you type their name.
1261
1266
1262 You can view a macro's contents by explicitly printing it with::
1267 You can view a macro's contents by explicitly printing it with::
1263
1268
1264 print macro_name
1269 print macro_name
1265
1270
1266 """
1271 """
1267 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1272 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1268 if not args: # List existing macros
1273 if not args: # List existing macros
1269 return sorted(k for k,v in iteritems(self.shell.user_ns) if\
1274 return sorted(k for k,v in iteritems(self.shell.user_ns) if\
1270 isinstance(v, Macro))
1275 isinstance(v, Macro))
1271 if len(args) == 1:
1276 if len(args) == 1:
1272 raise UsageError(
1277 raise UsageError(
1273 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1278 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1274 name, codefrom = args[0], " ".join(args[1:])
1279 name, codefrom = args[0], " ".join(args[1:])
1275
1280
1276 #print 'rng',ranges # dbg
1281 #print 'rng',ranges # dbg
1277 try:
1282 try:
1278 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1283 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1279 except (ValueError, TypeError) as e:
1284 except (ValueError, TypeError) as e:
1280 print(e.args[0])
1285 print(e.args[0])
1281 return
1286 return
1282 macro = Macro(lines)
1287 macro = Macro(lines)
1283 self.shell.define_macro(name, macro)
1288 self.shell.define_macro(name, macro)
1284 if not ( 'q' in opts) :
1289 if not ( 'q' in opts) :
1285 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1290 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1286 print('=== Macro contents: ===')
1291 print('=== Macro contents: ===')
1287 print(macro, end=' ')
1292 print(macro, end=' ')
1288
1293
1289 @magic_arguments.magic_arguments()
1294 @magic_arguments.magic_arguments()
1290 @magic_arguments.argument('output', type=str, default='', nargs='?',
1295 @magic_arguments.argument('output', type=str, default='', nargs='?',
1291 help="""The name of the variable in which to store output.
1296 help="""The name of the variable in which to store output.
1292 This is a utils.io.CapturedIO object with stdout/err attributes
1297 This is a utils.io.CapturedIO object with stdout/err attributes
1293 for the text of the captured output.
1298 for the text of the captured output.
1294
1299
1295 CapturedOutput also has a show() method for displaying the output,
1300 CapturedOutput also has a show() method for displaying the output,
1296 and __call__ as well, so you can use that to quickly display the
1301 and __call__ as well, so you can use that to quickly display the
1297 output.
1302 output.
1298
1303
1299 If unspecified, captured output is discarded.
1304 If unspecified, captured output is discarded.
1300 """
1305 """
1301 )
1306 )
1302 @magic_arguments.argument('--no-stderr', action="store_true",
1307 @magic_arguments.argument('--no-stderr', action="store_true",
1303 help="""Don't capture stderr."""
1308 help="""Don't capture stderr."""
1304 )
1309 )
1305 @magic_arguments.argument('--no-stdout', action="store_true",
1310 @magic_arguments.argument('--no-stdout', action="store_true",
1306 help="""Don't capture stdout."""
1311 help="""Don't capture stdout."""
1307 )
1312 )
1308 @magic_arguments.argument('--no-display', action="store_true",
1313 @magic_arguments.argument('--no-display', action="store_true",
1309 help="""Don't capture IPython's rich display."""
1314 help="""Don't capture IPython's rich display."""
1310 )
1315 )
1311 @cell_magic
1316 @cell_magic
1312 def capture(self, line, cell):
1317 def capture(self, line, cell):
1313 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1318 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1314 args = magic_arguments.parse_argstring(self.capture, line)
1319 args = magic_arguments.parse_argstring(self.capture, line)
1315 out = not args.no_stdout
1320 out = not args.no_stdout
1316 err = not args.no_stderr
1321 err = not args.no_stderr
1317 disp = not args.no_display
1322 disp = not args.no_display
1318 with capture_output(out, err, disp) as io:
1323 with capture_output(out, err, disp) as io:
1319 self.shell.run_cell(cell)
1324 self.shell.run_cell(cell)
1320 if args.output:
1325 if args.output:
1321 self.shell.user_ns[args.output] = io
1326 self.shell.user_ns[args.output] = io
1322
1327
1323 def parse_breakpoint(text, current_file):
1328 def parse_breakpoint(text, current_file):
1324 '''Returns (file, line) for file:line and (current_file, line) for line'''
1329 '''Returns (file, line) for file:line and (current_file, line) for line'''
1325 colon = text.find(':')
1330 colon = text.find(':')
1326 if colon == -1:
1331 if colon == -1:
1327 return current_file, int(text)
1332 return current_file, int(text)
1328 else:
1333 else:
1329 return text[:colon], int(text[colon+1:])
1334 return text[:colon], int(text[colon+1:])
1330
1335
1331 def _format_time(timespan, precision=3):
1336 def _format_time(timespan, precision=3):
1332 """Formats the timespan in a human readable form"""
1337 """Formats the timespan in a human readable form"""
1333
1338
1334 if timespan >= 60.0:
1339 if timespan >= 60.0:
1335 # we have more than a minute, format that in a human readable form
1340 # we have more than a minute, format that in a human readable form
1336 # Idea from http://snipplr.com/view/5713/
1341 # Idea from http://snipplr.com/view/5713/
1337 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1342 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1338 time = []
1343 time = []
1339 leftover = timespan
1344 leftover = timespan
1340 for suffix, length in parts:
1345 for suffix, length in parts:
1341 value = int(leftover / length)
1346 value = int(leftover / length)
1342 if value > 0:
1347 if value > 0:
1343 leftover = leftover % length
1348 leftover = leftover % length
1344 time.append(u'%s%s' % (str(value), suffix))
1349 time.append(u'%s%s' % (str(value), suffix))
1345 if leftover < 1:
1350 if leftover < 1:
1346 break
1351 break
1347 return " ".join(time)
1352 return " ".join(time)
1348
1353
1349
1354
1350 # Unfortunately the unicode 'micro' symbol can cause problems in
1355 # Unfortunately the unicode 'micro' symbol can cause problems in
1351 # certain terminals.
1356 # certain terminals.
1352 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1357 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1353 # Try to prevent crashes by being more secure than it needs to
1358 # Try to prevent crashes by being more secure than it needs to
1354 # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
1359 # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
1355 units = [u"s", u"ms",u'us',"ns"] # the save value
1360 units = [u"s", u"ms",u'us',"ns"] # the save value
1356 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1361 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1357 try:
1362 try:
1358 u'\xb5'.encode(sys.stdout.encoding)
1363 u'\xb5'.encode(sys.stdout.encoding)
1359 units = [u"s", u"ms",u'\xb5s',"ns"]
1364 units = [u"s", u"ms",u'\xb5s',"ns"]
1360 except:
1365 except:
1361 pass
1366 pass
1362 scaling = [1, 1e3, 1e6, 1e9]
1367 scaling = [1, 1e3, 1e6, 1e9]
1363
1368
1364 if timespan > 0.0:
1369 if timespan > 0.0:
1365 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1370 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1366 else:
1371 else:
1367 order = 3
1372 order = 3
1368 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
1373 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
General Comments 0
You need to be logged in to leave comments. Login now