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