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