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