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