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