##// END OF EJS Templates
Use pathlib in magics module's execution.py
Nick Muoh -
Show More
@@ -1,1498 +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(
364 print(
364 f"\n*** Profile stats marshalled to file {repr(dump_file)}.{sys_exit}"
365 f"\n*** Profile stats marshalled to file {repr(dump_file)}.{sys_exit}"
365 )
366 )
366 if text_file:
367 if text_file:
367 Path(text_file).write_text(output)
368 pfile = Path(text_file)
369 pfile.touch(exist_ok=True)
370 pfile.write_text(output)
371
368 print(
372 print(
369 f"\n*** Profile printout saved to text file {repr(text_file)}.{sys_exit}"
373 f"\n*** Profile printout saved to text file {repr(text_file)}.{sys_exit}"
370 )
374 )
371
375
372 if 'r' in opts:
376 if 'r' in opts:
373 return stats
377 return stats
374
378
375 return None
379 return None
376
380
377 @line_magic
381 @line_magic
378 def pdb(self, parameter_s=''):
382 def pdb(self, parameter_s=''):
379 """Control the automatic calling of the pdb interactive debugger.
383 """Control the automatic calling of the pdb interactive debugger.
380
384
381 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
382 argument it works as a toggle.
386 argument it works as a toggle.
383
387
384 When an exception is triggered, IPython can optionally call the
388 When an exception is triggered, IPython can optionally call the
385 interactive pdb debugger after the traceback printout. %pdb toggles
389 interactive pdb debugger after the traceback printout. %pdb toggles
386 this feature on and off.
390 this feature on and off.
387
391
388 The initial state of this feature is set in your configuration
392 The initial state of this feature is set in your configuration
389 file (the option is ``InteractiveShell.pdb``).
393 file (the option is ``InteractiveShell.pdb``).
390
394
391 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,
392 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
393 the %debug magic."""
397 the %debug magic."""
394
398
395 par = parameter_s.strip().lower()
399 par = parameter_s.strip().lower()
396
400
397 if par:
401 if par:
398 try:
402 try:
399 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
403 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
400 except KeyError:
404 except KeyError:
401 print ('Incorrect argument. Use on/1, off/0, '
405 print ('Incorrect argument. Use on/1, off/0, '
402 'or nothing for a toggle.')
406 'or nothing for a toggle.')
403 return
407 return
404 else:
408 else:
405 # toggle
409 # toggle
406 new_pdb = not self.shell.call_pdb
410 new_pdb = not self.shell.call_pdb
407
411
408 # set on the shell
412 # set on the shell
409 self.shell.call_pdb = new_pdb
413 self.shell.call_pdb = new_pdb
410 print('Automatic pdb calling has been turned',on_off(new_pdb))
414 print('Automatic pdb calling has been turned',on_off(new_pdb))
411
415
412 @skip_doctest
416 @skip_doctest
413 @magic_arguments.magic_arguments()
417 @magic_arguments.magic_arguments()
414 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
418 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
415 help="""
419 help="""
416 Set break point at LINE in FILE.
420 Set break point at LINE in FILE.
417 """
421 """
418 )
422 )
419 @magic_arguments.argument('statement', nargs='*',
423 @magic_arguments.argument('statement', nargs='*',
420 help="""
424 help="""
421 Code to run in debugger.
425 Code to run in debugger.
422 You can omit this in cell magic mode.
426 You can omit this in cell magic mode.
423 """
427 """
424 )
428 )
425 @no_var_expand
429 @no_var_expand
426 @line_cell_magic
430 @line_cell_magic
427 def debug(self, line='', cell=None):
431 def debug(self, line='', cell=None):
428 """Activate the interactive debugger.
432 """Activate the interactive debugger.
429
433
430 This magic command support two ways of activating debugger.
434 This magic command support two ways of activating debugger.
431 One is to activate debugger before executing code. This way, you
435 One is to activate debugger before executing code. This way, you
432 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.
433 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
434 a breakpoint.
438 a breakpoint.
435
439
436 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
437 activate this mode simply running %debug without any argument.
441 activate this mode simply running %debug without any argument.
438 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
439 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
440 traceback that occurred, so you must call this quickly after an
444 traceback that occurred, so you must call this quickly after an
441 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
442 occurs, it clobbers the previous one.
446 occurs, it clobbers the previous one.
443
447
444 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
445 the %pdb magic for more details.
449 the %pdb magic for more details.
446
450
447 .. versionchanged:: 7.3
451 .. versionchanged:: 7.3
448 When running code, user variables are no longer expanded,
452 When running code, user variables are no longer expanded,
449 the magic line is always left unmodified.
453 the magic line is always left unmodified.
450
454
451 """
455 """
452 args = magic_arguments.parse_argstring(self.debug, line)
456 args = magic_arguments.parse_argstring(self.debug, line)
453
457
454 if not (args.breakpoint or args.statement or cell):
458 if not (args.breakpoint or args.statement or cell):
455 self._debug_post_mortem()
459 self._debug_post_mortem()
456 elif not (args.breakpoint or cell):
460 elif not (args.breakpoint or cell):
457 # 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
458 self._debug_exec(line, None)
462 self._debug_exec(line, None)
459 else:
463 else:
460 # Here we try to reconstruct the code from the output of
464 # Here we try to reconstruct the code from the output of
461 # parse_argstring. This might not work if the code has spaces
465 # parse_argstring. This might not work if the code has spaces
462 # For example this fails for `print("a b")`
466 # For example this fails for `print("a b")`
463 code = "\n".join(args.statement)
467 code = "\n".join(args.statement)
464 if cell:
468 if cell:
465 code += "\n" + cell
469 code += "\n" + cell
466 self._debug_exec(code, args.breakpoint)
470 self._debug_exec(code, args.breakpoint)
467
471
468 def _debug_post_mortem(self):
472 def _debug_post_mortem(self):
469 self.shell.debugger(force=True)
473 self.shell.debugger(force=True)
470
474
471 def _debug_exec(self, code, breakpoint):
475 def _debug_exec(self, code, breakpoint):
472 if breakpoint:
476 if breakpoint:
473 (filename, bp_line) = breakpoint.rsplit(':', 1)
477 (filename, bp_line) = breakpoint.rsplit(':', 1)
474 bp_line = int(bp_line)
478 bp_line = int(bp_line)
475 else:
479 else:
476 (filename, bp_line) = (None, None)
480 (filename, bp_line) = (None, None)
477 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)
478
482
479 @line_magic
483 @line_magic
480 def tb(self, s):
484 def tb(self, s):
481 """Print the last traceback.
485 """Print the last traceback.
482
486
483 Optionally, specify an exception reporting mode, tuning the
487 Optionally, specify an exception reporting mode, tuning the
484 verbosity of the traceback. By default the currently-active exception
488 verbosity of the traceback. By default the currently-active exception
485 mode is used. See %xmode for changing exception reporting modes.
489 mode is used. See %xmode for changing exception reporting modes.
486
490
487 Valid modes: Plain, Context, Verbose, and Minimal.
491 Valid modes: Plain, Context, Verbose, and Minimal.
488 """
492 """
489 interactive_tb = self.shell.InteractiveTB
493 interactive_tb = self.shell.InteractiveTB
490 if s:
494 if s:
491 # Switch exception reporting mode for this one call.
495 # Switch exception reporting mode for this one call.
492 # Ensure it is switched back.
496 # Ensure it is switched back.
493 def xmode_switch_err(name):
497 def xmode_switch_err(name):
494 warn('Error changing %s exception modes.\n%s' %
498 warn('Error changing %s exception modes.\n%s' %
495 (name,sys.exc_info()[1]))
499 (name,sys.exc_info()[1]))
496
500
497 new_mode = s.strip().capitalize()
501 new_mode = s.strip().capitalize()
498 original_mode = interactive_tb.mode
502 original_mode = interactive_tb.mode
499 try:
503 try:
500 try:
504 try:
501 interactive_tb.set_mode(mode=new_mode)
505 interactive_tb.set_mode(mode=new_mode)
502 except Exception:
506 except Exception:
503 xmode_switch_err('user')
507 xmode_switch_err('user')
504 else:
508 else:
505 self.shell.showtraceback()
509 self.shell.showtraceback()
506 finally:
510 finally:
507 interactive_tb.set_mode(mode=original_mode)
511 interactive_tb.set_mode(mode=original_mode)
508 else:
512 else:
509 self.shell.showtraceback()
513 self.shell.showtraceback()
510
514
511 @skip_doctest
515 @skip_doctest
512 @line_magic
516 @line_magic
513 def run(self, parameter_s='', runner=None,
517 def run(self, parameter_s='', runner=None,
514 file_finder=get_py_filename):
518 file_finder=get_py_filename):
515 """Run the named file inside IPython as a program.
519 """Run the named file inside IPython as a program.
516
520
517 Usage::
521 Usage::
518
522
519 %run [-n -i -e -G]
523 %run [-n -i -e -G]
520 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
524 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
521 ( -m mod | file ) [args]
525 ( -m mod | file ) [args]
522
526
523 Parameters after the filename are passed as command-line arguments to
527 Parameters after the filename are passed as command-line arguments to
524 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
525 prompt.
529 prompt.
526
530
527 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``,
528 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
529 loading all variables into your interactive namespace for further use
533 loading all variables into your interactive namespace for further use
530 (unless -p is used, see below).
534 (unless -p is used, see below).
531
535
532 The file is executed in a namespace initially consisting only of
536 The file is executed in a namespace initially consisting only of
533 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
537 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
534 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
535 (except for sharing global objects such as previously imported
539 (except for sharing global objects such as previously imported
536 modules). But after execution, the IPython interactive namespace gets
540 modules). But after execution, the IPython interactive namespace gets
537 updated with all variables defined in the program (except for __name__
541 updated with all variables defined in the program (except for __name__
538 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
539 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.
540
544
541 Arguments are expanded using shell-like glob match. Patterns
545 Arguments are expanded using shell-like glob match. Patterns
542 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
546 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
543 tilde '~' will be expanded into user's home directory. Unlike
547 tilde '~' will be expanded into user's home directory. Unlike
544 real shells, quotation does not suppress expansions. Use
548 real shells, quotation does not suppress expansions. Use
545 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
549 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
546 To completely disable these expansions, you can use -G flag.
550 To completely disable these expansions, you can use -G flag.
547
551
548 On Windows systems, the use of single quotes `'` when specifying
552 On Windows systems, the use of single quotes `'` when specifying
549 a file is not supported. Use double quotes `"`.
553 a file is not supported. Use double quotes `"`.
550
554
551 Options:
555 Options:
552
556
553 -n
557 -n
554 __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
555 without extension (as python does under import). This allows running
559 without extension (as python does under import). This allows running
556 scripts and reloading the definitions in them without calling code
560 scripts and reloading the definitions in them without calling code
557 protected by an ``if __name__ == "__main__"`` clause.
561 protected by an ``if __name__ == "__main__"`` clause.
558
562
559 -i
563 -i
560 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
561 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
562 which depends on variables defined interactively.
566 which depends on variables defined interactively.
563
567
564 -e
568 -e
565 ignore sys.exit() calls or SystemExit exceptions in the script
569 ignore sys.exit() calls or SystemExit exceptions in the script
566 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
567 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
568 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
569 seeing a traceback of the unittest module.
573 seeing a traceback of the unittest module.
570
574
571 -t
575 -t
572 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
573 you an estimated CPU time consumption for your script, which under
577 you an estimated CPU time consumption for your script, which under
574 Unix uses the resource module to avoid the wraparound problems of
578 Unix uses the resource module to avoid the wraparound problems of
575 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
576 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).
577
581
578 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>
579 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
580 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.
581
585
582 For example (testing the script uniq_stable.py)::
586 For example (testing the script uniq_stable.py)::
583
587
584 In [1]: run -t uniq_stable
588 In [1]: run -t uniq_stable
585
589
586 IPython CPU timings (estimated):
590 IPython CPU timings (estimated):
587 User : 0.19597 s.
591 User : 0.19597 s.
588 System: 0.0 s.
592 System: 0.0 s.
589
593
590 In [2]: run -t -N5 uniq_stable
594 In [2]: run -t -N5 uniq_stable
591
595
592 IPython CPU timings (estimated):
596 IPython CPU timings (estimated):
593 Total runs performed: 5
597 Total runs performed: 5
594 Times : Total Per run
598 Times : Total Per run
595 User : 0.910862 s, 0.1821724 s.
599 User : 0.910862 s, 0.1821724 s.
596 System: 0.0 s, 0.0 s.
600 System: 0.0 s, 0.0 s.
597
601
598 -d
602 -d
599 run your program under the control of pdb, the Python debugger.
603 run your program under the control of pdb, the Python debugger.
600 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,
601 etc. Internally, what IPython does is similar to calling::
605 etc. Internally, what IPython does is similar to calling::
602
606
603 pdb.run('execfile("YOURFILENAME")')
607 pdb.run('execfile("YOURFILENAME")')
604
608
605 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
606 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
607 (where N must be an integer). For example::
611 (where N must be an integer). For example::
608
612
609 %run -d -b40 myscript
613 %run -d -b40 myscript
610
614
611 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
612 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
613 something (not a comment or docstring) for it to stop execution.
617 something (not a comment or docstring) for it to stop execution.
614
618
615 Or you can specify a breakpoint in a different file::
619 Or you can specify a breakpoint in a different file::
616
620
617 %run -d -b myotherfile.py:20 myscript
621 %run -d -b myotherfile.py:20 myscript
618
622
619 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
620 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
621 breakpoint.
625 breakpoint.
622
626
623 Entering 'help' gives information about the use of the debugger. You
627 Entering 'help' gives information about the use of the debugger. You
624 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()"
625 at a prompt.
629 at a prompt.
626
630
627 -p
631 -p
628 run program under the control of the Python profiler module (which
632 run program under the control of the Python profiler module (which
629 prints a detailed report of execution times, function calls, etc).
633 prints a detailed report of execution times, function calls, etc).
630
634
631 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
632 profiler itself. See the docs for %prun for details.
636 profiler itself. See the docs for %prun for details.
633
637
634 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
635 IPython interactive namespace (because they remain in the namespace
639 IPython interactive namespace (because they remain in the namespace
636 where the profiler executes them).
640 where the profiler executes them).
637
641
638 Internally this triggers a call to %prun, see its documentation for
642 Internally this triggers a call to %prun, see its documentation for
639 details on the options available specifically for profiling.
643 details on the options available specifically for profiling.
640
644
641 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:
642 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,
643 just as if the commands were written on IPython prompt.
647 just as if the commands were written on IPython prompt.
644
648
645 -m
649 -m
646 specify module name to load instead of script path. Similar to
650 specify module name to load instead of script path. Similar to
647 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
648 want to combine with other %run options. Unlike the python interpreter
652 want to combine with other %run options. Unlike the python interpreter
649 only source modules are allowed no .pyc or .pyo files.
653 only source modules are allowed no .pyc or .pyo files.
650 For example::
654 For example::
651
655
652 %run -m example
656 %run -m example
653
657
654 will run the example module.
658 will run the example module.
655
659
656 -G
660 -G
657 disable shell-like glob expansion of arguments.
661 disable shell-like glob expansion of arguments.
658
662
659 """
663 """
660
664
661 # Logic to handle issue #3664
665 # Logic to handle issue #3664
662 # 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.
663 if '-m' in parameter_s and '--' not in parameter_s:
667 if '-m' in parameter_s and '--' not in parameter_s:
664 argv = shlex.split(parameter_s, posix=(os.name == 'posix'))
668 argv = shlex.split(parameter_s, posix=(os.name == 'posix'))
665 for idx, arg in enumerate(argv):
669 for idx, arg in enumerate(argv):
666 if arg and arg.startswith('-') and arg != '-':
670 if arg and arg.startswith('-') and arg != '-':
667 if arg == '-m':
671 if arg == '-m':
668 argv.insert(idx + 2, '--')
672 argv.insert(idx + 2, '--')
669 break
673 break
670 else:
674 else:
671 # Positional arg, break
675 # Positional arg, break
672 break
676 break
673 parameter_s = ' '.join(shlex.quote(arg) for arg in argv)
677 parameter_s = ' '.join(shlex.quote(arg) for arg in argv)
674
678
675 # get arguments and set sys.argv for program to be run.
679 # get arguments and set sys.argv for program to be run.
676 opts, arg_lst = self.parse_options(parameter_s,
680 opts, arg_lst = self.parse_options(parameter_s,
677 'nidtN:b:pD:l:rs:T:em:G',
681 'nidtN:b:pD:l:rs:T:em:G',
678 mode='list', list_all=1)
682 mode='list', list_all=1)
679 if "m" in opts:
683 if "m" in opts:
680 modulename = opts["m"][0]
684 modulename = opts["m"][0]
681 modpath = find_mod(modulename)
685 modpath = find_mod(modulename)
682 if modpath is None:
686 if modpath is None:
683 msg = '%r is not a valid modulename on sys.path'%modulename
687 msg = '%r is not a valid modulename on sys.path'%modulename
684 raise Exception(msg)
688 raise Exception(msg)
685 arg_lst = [modpath] + arg_lst
689 arg_lst = [modpath] + arg_lst
686 try:
690 try:
687 fpath = None # initialize to make sure fpath is in scope later
691 fpath = None # initialize to make sure fpath is in scope later
688 fpath = arg_lst[0]
692 fpath = arg_lst[0]
689 filename = file_finder(fpath)
693 filename = file_finder(fpath)
690 except IndexError as e:
694 except IndexError as e:
691 msg = 'you must provide at least a filename.'
695 msg = 'you must provide at least a filename.'
692 raise Exception(msg) from e
696 raise Exception(msg) from e
693 except IOError as e:
697 except IOError as e:
694 try:
698 try:
695 msg = str(e)
699 msg = str(e)
696 except UnicodeError:
700 except UnicodeError:
697 msg = e.message
701 msg = e.message
698 if os.name == 'nt' and re.match(r"^'.*'$",fpath):
702 if os.name == 'nt' and re.match(r"^'.*'$",fpath):
699 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"')
700 raise Exception(msg) from e
704 raise Exception(msg) from e
701 except TypeError:
705 except TypeError:
702 if fpath in sys.meta_path:
706 if fpath in sys.meta_path:
703 filename = ""
707 filename = ""
704 else:
708 else:
705 raise
709 raise
706
710
707 if filename.lower().endswith(('.ipy', '.ipynb')):
711 if filename.lower().endswith(('.ipy', '.ipynb')):
708 with preserve_keys(self.shell.user_ns, '__file__'):
712 with preserve_keys(self.shell.user_ns, '__file__'):
709 self.shell.user_ns['__file__'] = filename
713 self.shell.user_ns['__file__'] = filename
710 self.shell.safe_execfile_ipy(filename, raise_exceptions=True)
714 self.shell.safe_execfile_ipy(filename, raise_exceptions=True)
711 return
715 return
712
716
713 # 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
714 exit_ignore = 'e' in opts
718 exit_ignore = 'e' in opts
715
719
716 # 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
717 # were run from a system shell.
721 # were run from a system shell.
718 save_argv = sys.argv # save it for later restoring
722 save_argv = sys.argv # save it for later restoring
719
723
720 if 'G' in opts:
724 if 'G' in opts:
721 args = arg_lst[1:]
725 args = arg_lst[1:]
722 else:
726 else:
723 # tilde and glob expansion
727 # tilde and glob expansion
724 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
728 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
725
729
726 sys.argv = [filename] + args # put in the proper filename
730 sys.argv = [filename] + args # put in the proper filename
727
731
728 if 'n' in opts:
732 if 'n' in opts:
729 name = Path(filename).stem
733 name = Path(filename).stem
730 else:
734 else:
731 name = '__main__'
735 name = '__main__'
732
736
733 if 'i' in opts:
737 if 'i' in opts:
734 # Run in user's interactive namespace
738 # Run in user's interactive namespace
735 prog_ns = self.shell.user_ns
739 prog_ns = self.shell.user_ns
736 __name__save = self.shell.user_ns['__name__']
740 __name__save = self.shell.user_ns['__name__']
737 prog_ns['__name__'] = name
741 prog_ns['__name__'] = name
738 main_mod = self.shell.user_module
742 main_mod = self.shell.user_module
739
743
740 # 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
741 # set the __file__ global in the script's namespace
745 # set the __file__ global in the script's namespace
742 # TK: Is this necessary in interactive mode?
746 # TK: Is this necessary in interactive mode?
743 prog_ns['__file__'] = filename
747 prog_ns['__file__'] = filename
744 else:
748 else:
745 # Run in a fresh, empty namespace
749 # Run in a fresh, empty namespace
746
750
747 # 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
748 # exits, the python deletion mechanism doesn't zero it out
752 # exits, the python deletion mechanism doesn't zero it out
749 # (leaving dangling references). See interactiveshell for details
753 # (leaving dangling references). See interactiveshell for details
750 main_mod = self.shell.new_main_mod(filename, name)
754 main_mod = self.shell.new_main_mod(filename, name)
751 prog_ns = main_mod.__dict__
755 prog_ns = main_mod.__dict__
752
756
753 # pickle fix. See interactiveshell for an explanation. But we need to
757 # pickle fix. See interactiveshell for an explanation. But we need to
754 # 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
755 main_mod_name = prog_ns['__name__']
759 main_mod_name = prog_ns['__name__']
756
760
757 if main_mod_name == '__main__':
761 if main_mod_name == '__main__':
758 restore_main = sys.modules['__main__']
762 restore_main = sys.modules['__main__']
759 else:
763 else:
760 restore_main = False
764 restore_main = False
761
765
762 # 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
763 # every single object ever created.
767 # every single object ever created.
764 sys.modules[main_mod_name] = main_mod
768 sys.modules[main_mod_name] = main_mod
765
769
766 if 'p' in opts or 'd' in opts:
770 if 'p' in opts or 'd' in opts:
767 if 'm' in opts:
771 if 'm' in opts:
768 code = 'run_module(modulename, prog_ns)'
772 code = 'run_module(modulename, prog_ns)'
769 code_ns = {
773 code_ns = {
770 'run_module': self.shell.safe_run_module,
774 'run_module': self.shell.safe_run_module,
771 'prog_ns': prog_ns,
775 'prog_ns': prog_ns,
772 'modulename': modulename,
776 'modulename': modulename,
773 }
777 }
774 else:
778 else:
775 if 'd' in opts:
779 if 'd' in opts:
776 # allow exceptions to raise in debug mode
780 # allow exceptions to raise in debug mode
777 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
781 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
778 else:
782 else:
779 code = 'execfile(filename, prog_ns)'
783 code = 'execfile(filename, prog_ns)'
780 code_ns = {
784 code_ns = {
781 'execfile': self.shell.safe_execfile,
785 'execfile': self.shell.safe_execfile,
782 'prog_ns': prog_ns,
786 'prog_ns': prog_ns,
783 'filename': get_py_filename(filename),
787 'filename': get_py_filename(filename),
784 }
788 }
785
789
786 try:
790 try:
787 stats = None
791 stats = None
788 if 'p' in opts:
792 if 'p' in opts:
789 stats = self._run_with_profiler(code, opts, code_ns)
793 stats = self._run_with_profiler(code, opts, code_ns)
790 else:
794 else:
791 if 'd' in opts:
795 if 'd' in opts:
792 bp_file, bp_line = parse_breakpoint(
796 bp_file, bp_line = parse_breakpoint(
793 opts.get('b', ['1'])[0], filename)
797 opts.get('b', ['1'])[0], filename)
794 self._run_with_debugger(
798 self._run_with_debugger(
795 code, code_ns, filename, bp_line, bp_file)
799 code, code_ns, filename, bp_line, bp_file)
796 else:
800 else:
797 if 'm' in opts:
801 if 'm' in opts:
798 def run():
802 def run():
799 self.shell.safe_run_module(modulename, prog_ns)
803 self.shell.safe_run_module(modulename, prog_ns)
800 else:
804 else:
801 if runner is None:
805 if runner is None:
802 runner = self.default_runner
806 runner = self.default_runner
803 if runner is None:
807 if runner is None:
804 runner = self.shell.safe_execfile
808 runner = self.shell.safe_execfile
805
809
806 def run():
810 def run():
807 runner(filename, prog_ns, prog_ns,
811 runner(filename, prog_ns, prog_ns,
808 exit_ignore=exit_ignore)
812 exit_ignore=exit_ignore)
809
813
810 if 't' in opts:
814 if 't' in opts:
811 # timed execution
815 # timed execution
812 try:
816 try:
813 nruns = int(opts['N'][0])
817 nruns = int(opts['N'][0])
814 if nruns < 1:
818 if nruns < 1:
815 error('Number of runs must be >=1')
819 error('Number of runs must be >=1')
816 return
820 return
817 except (KeyError):
821 except (KeyError):
818 nruns = 1
822 nruns = 1
819 self._run_with_timing(run, nruns)
823 self._run_with_timing(run, nruns)
820 else:
824 else:
821 # regular execution
825 # regular execution
822 run()
826 run()
823
827
824 if 'i' in opts:
828 if 'i' in opts:
825 self.shell.user_ns['__name__'] = __name__save
829 self.shell.user_ns['__name__'] = __name__save
826 else:
830 else:
827 # update IPython interactive namespace
831 # update IPython interactive namespace
828
832
829 # Some forms of read errors on the file may mean the
833 # Some forms of read errors on the file may mean the
830 # __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
831 # worry about a possible KeyError.
835 # worry about a possible KeyError.
832 prog_ns.pop('__name__', None)
836 prog_ns.pop('__name__', None)
833
837
834 with preserve_keys(self.shell.user_ns, '__file__'):
838 with preserve_keys(self.shell.user_ns, '__file__'):
835 self.shell.user_ns.update(prog_ns)
839 self.shell.user_ns.update(prog_ns)
836 finally:
840 finally:
837 # 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
838 # 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
839 # %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
840 # at all, and similar problems have been reported before:
844 # at all, and similar problems have been reported before:
841 # 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
842 # 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
843 # 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
844 # exit.
848 # exit.
845 self.shell.user_ns['__builtins__'] = builtin_mod
849 self.shell.user_ns['__builtins__'] = builtin_mod
846
850
847 # Ensure key global structures are restored
851 # Ensure key global structures are restored
848 sys.argv = save_argv
852 sys.argv = save_argv
849 if restore_main:
853 if restore_main:
850 sys.modules['__main__'] = restore_main
854 sys.modules['__main__'] = restore_main
851 if '__mp_main__' in sys.modules:
855 if '__mp_main__' in sys.modules:
852 sys.modules['__mp_main__'] = restore_main
856 sys.modules['__mp_main__'] = restore_main
853 else:
857 else:
854 # Remove from sys.modules the reference to main_mod we'd
858 # Remove from sys.modules the reference to main_mod we'd
855 # added. Otherwise it will trap references to objects
859 # added. Otherwise it will trap references to objects
856 # contained therein.
860 # contained therein.
857 del sys.modules[main_mod_name]
861 del sys.modules[main_mod_name]
858
862
859 return stats
863 return stats
860
864
861 def _run_with_debugger(self, code, code_ns, filename=None,
865 def _run_with_debugger(self, code, code_ns, filename=None,
862 bp_line=None, bp_file=None):
866 bp_line=None, bp_file=None):
863 """
867 """
864 Run `code` in debugger with a break point.
868 Run `code` in debugger with a break point.
865
869
866 Parameters
870 Parameters
867 ----------
871 ----------
868 code : str
872 code : str
869 Code to execute.
873 Code to execute.
870 code_ns : dict
874 code_ns : dict
871 A namespace in which `code` is executed.
875 A namespace in which `code` is executed.
872 filename : str
876 filename : str
873 `code` is ran as if it is in `filename`.
877 `code` is ran as if it is in `filename`.
874 bp_line : int, optional
878 bp_line : int, optional
875 Line number of the break point.
879 Line number of the break point.
876 bp_file : str, optional
880 bp_file : str, optional
877 Path to the file in which break point is specified.
881 Path to the file in which break point is specified.
878 `filename` is used if not given.
882 `filename` is used if not given.
879
883
880 Raises
884 Raises
881 ------
885 ------
882 UsageError
886 UsageError
883 If the break point given by `bp_line` is not valid.
887 If the break point given by `bp_line` is not valid.
884
888
885 """
889 """
886 deb = self.shell.InteractiveTB.pdb
890 deb = self.shell.InteractiveTB.pdb
887 if not deb:
891 if not deb:
888 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
892 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
889 deb = self.shell.InteractiveTB.pdb
893 deb = self.shell.InteractiveTB.pdb
890
894
891 # 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
892 # handle it not existing. https://github.com/ipython/ipython/issues/10028
896 # handle it not existing. https://github.com/ipython/ipython/issues/10028
893 if hasattr(deb, 'curframe'):
897 if hasattr(deb, 'curframe'):
894 del deb.curframe
898 del deb.curframe
895
899
896 # reset Breakpoint state, which is moronically kept
900 # reset Breakpoint state, which is moronically kept
897 # in a class
901 # in a class
898 bdb.Breakpoint.next = 1
902 bdb.Breakpoint.next = 1
899 bdb.Breakpoint.bplist = {}
903 bdb.Breakpoint.bplist = {}
900 bdb.Breakpoint.bpbynumber = [None]
904 bdb.Breakpoint.bpbynumber = [None]
901 deb.clear_all_breaks()
905 deb.clear_all_breaks()
902 if bp_line is not None:
906 if bp_line is not None:
903 # Set an initial breakpoint to stop execution
907 # Set an initial breakpoint to stop execution
904 maxtries = 10
908 maxtries = 10
905 bp_file = bp_file or filename
909 bp_file = bp_file or filename
906 checkline = deb.checkline(bp_file, bp_line)
910 checkline = deb.checkline(bp_file, bp_line)
907 if not checkline:
911 if not checkline:
908 for bp in range(bp_line + 1, bp_line + maxtries + 1):
912 for bp in range(bp_line + 1, bp_line + maxtries + 1):
909 if deb.checkline(bp_file, bp):
913 if deb.checkline(bp_file, bp):
910 break
914 break
911 else:
915 else:
912 msg = ("\nI failed to find a valid line to set "
916 msg = ("\nI failed to find a valid line to set "
913 "a breakpoint\n"
917 "a breakpoint\n"
914 "after trying up to line: %s.\n"
918 "after trying up to line: %s.\n"
915 "Please set a valid breakpoint manually "
919 "Please set a valid breakpoint manually "
916 "with the -b option." % bp)
920 "with the -b option." % bp)
917 raise UsageError(msg)
921 raise UsageError(msg)
918 # if we find a good linenumber, set the breakpoint
922 # if we find a good linenumber, set the breakpoint
919 deb.do_break('%s:%s' % (bp_file, bp_line))
923 deb.do_break('%s:%s' % (bp_file, bp_line))
920
924
921 if filename:
925 if filename:
922 # Mimic Pdb._runscript(...)
926 # Mimic Pdb._runscript(...)
923 deb._wait_for_mainpyfile = True
927 deb._wait_for_mainpyfile = True
924 deb.mainpyfile = deb.canonic(filename)
928 deb.mainpyfile = deb.canonic(filename)
925
929
926 # Start file run
930 # Start file run
927 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)
928 try:
932 try:
929 if filename:
933 if filename:
930 # 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
931 deb._exec_filename = filename
935 deb._exec_filename = filename
932 while True:
936 while True:
933 try:
937 try:
934 trace = sys.gettrace()
938 trace = sys.gettrace()
935 deb.run(code, code_ns)
939 deb.run(code, code_ns)
936 except Restart:
940 except Restart:
937 print("Restarting")
941 print("Restarting")
938 if filename:
942 if filename:
939 deb._wait_for_mainpyfile = True
943 deb._wait_for_mainpyfile = True
940 deb.mainpyfile = deb.canonic(filename)
944 deb.mainpyfile = deb.canonic(filename)
941 continue
945 continue
942 else:
946 else:
943 break
947 break
944 finally:
948 finally:
945 sys.settrace(trace)
949 sys.settrace(trace)
946
950
947
951
948 except:
952 except:
949 etype, value, tb = sys.exc_info()
953 etype, value, tb = sys.exc_info()
950 # Skip three frames in the traceback: the %run one,
954 # Skip three frames in the traceback: the %run one,
951 # one inside bdb.py, and the command-line typed by the
955 # one inside bdb.py, and the command-line typed by the
952 # user (run by exec in pdb itself).
956 # user (run by exec in pdb itself).
953 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
957 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
954
958
955 @staticmethod
959 @staticmethod
956 def _run_with_timing(run, nruns):
960 def _run_with_timing(run, nruns):
957 """
961 """
958 Run function `run` and print timing information.
962 Run function `run` and print timing information.
959
963
960 Parameters
964 Parameters
961 ----------
965 ----------
962 run : callable
966 run : callable
963 Any callable object which takes no argument.
967 Any callable object which takes no argument.
964 nruns : int
968 nruns : int
965 Number of times to execute `run`.
969 Number of times to execute `run`.
966
970
967 """
971 """
968 twall0 = time.perf_counter()
972 twall0 = time.perf_counter()
969 if nruns == 1:
973 if nruns == 1:
970 t0 = clock2()
974 t0 = clock2()
971 run()
975 run()
972 t1 = clock2()
976 t1 = clock2()
973 t_usr = t1[0] - t0[0]
977 t_usr = t1[0] - t0[0]
974 t_sys = t1[1] - t0[1]
978 t_sys = t1[1] - t0[1]
975 print("\nIPython CPU timings (estimated):")
979 print("\nIPython CPU timings (estimated):")
976 print(" User : %10.2f s." % t_usr)
980 print(" User : %10.2f s." % t_usr)
977 print(" System : %10.2f s." % t_sys)
981 print(" System : %10.2f s." % t_sys)
978 else:
982 else:
979 runs = range(nruns)
983 runs = range(nruns)
980 t0 = clock2()
984 t0 = clock2()
981 for nr in runs:
985 for nr in runs:
982 run()
986 run()
983 t1 = clock2()
987 t1 = clock2()
984 t_usr = t1[0] - t0[0]
988 t_usr = t1[0] - t0[0]
985 t_sys = t1[1] - t0[1]
989 t_sys = t1[1] - t0[1]
986 print("\nIPython CPU timings (estimated):")
990 print("\nIPython CPU timings (estimated):")
987 print("Total runs performed:", nruns)
991 print("Total runs performed:", nruns)
988 print(" Times : %10s %10s" % ('Total', 'Per run'))
992 print(" Times : %10s %10s" % ('Total', 'Per run'))
989 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))
990 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))
991 twall1 = time.perf_counter()
995 twall1 = time.perf_counter()
992 print("Wall time: %10.2f s." % (twall1 - twall0))
996 print("Wall time: %10.2f s." % (twall1 - twall0))
993
997
994 @skip_doctest
998 @skip_doctest
995 @no_var_expand
999 @no_var_expand
996 @line_cell_magic
1000 @line_cell_magic
997 @needs_local_scope
1001 @needs_local_scope
998 def timeit(self, line='', cell=None, local_ns=None):
1002 def timeit(self, line='', cell=None, local_ns=None):
999 """Time execution of a Python statement or expression
1003 """Time execution of a Python statement or expression
1000
1004
1001 Usage, in line mode:
1005 Usage, in line mode:
1002 %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
1003 or in cell mode:
1007 or in cell mode:
1004 %%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
1005 code
1009 code
1006 code...
1010 code...
1007
1011
1008 Time execution of a Python statement or expression using the timeit
1012 Time execution of a Python statement or expression using the timeit
1009 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:
1010
1014
1011 - 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
1012 ones can be chained with using semicolons).
1016 ones can be chained with using semicolons).
1013
1017
1014 - 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
1015 (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
1016 body has access to any variables created in the setup code.
1020 body has access to any variables created in the setup code.
1017
1021
1018 Options:
1022 Options:
1019 -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
1020 provided, <N> is determined so as to get sufficient accuracy.
1024 provided, <N> is determined so as to get sufficient accuracy.
1021
1025
1022 -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
1023 best result.
1027 best result.
1024 Default: 7
1028 Default: 7
1025
1029
1026 -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.
1027 This function measures wall time.
1031 This function measures wall time.
1028
1032
1029 -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
1030 Windows and measures wall time. On Unix, resource.getrusage is used
1034 Windows and measures wall time. On Unix, resource.getrusage is used
1031 instead and returns the CPU user time.
1035 instead and returns the CPU user time.
1032
1036
1033 -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.
1034 Default: 3
1038 Default: 3
1035
1039
1036 -q: Quiet, do not print result.
1040 -q: Quiet, do not print result.
1037
1041
1038 -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
1039 the result in more details.
1043 the result in more details.
1040
1044
1041 .. versionchanged:: 7.3
1045 .. versionchanged:: 7.3
1042 User variables are no longer expanded,
1046 User variables are no longer expanded,
1043 the magic line is always left unmodified.
1047 the magic line is always left unmodified.
1044
1048
1045 Examples
1049 Examples
1046 --------
1050 --------
1047 ::
1051 ::
1048
1052
1049 In [1]: %timeit pass
1053 In [1]: %timeit pass
1050 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)
1051
1055
1052 In [2]: u = None
1056 In [2]: u = None
1053
1057
1054 In [3]: %timeit u is None
1058 In [3]: %timeit u is None
1055 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)
1056
1060
1057 In [4]: %timeit -r 4 u == None
1061 In [4]: %timeit -r 4 u == None
1058
1062
1059 In [5]: import time
1063 In [5]: import time
1060
1064
1061 In [6]: %timeit -n1 time.sleep(2)
1065 In [6]: %timeit -n1 time.sleep(2)
1062
1066
1063
1067
1064 The times reported by %timeit will be slightly higher than those
1068 The times reported by %timeit will be slightly higher than those
1065 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
1066 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
1067 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
1068 statement to import function or create variables. Generally, the bias
1072 statement to import function or create variables. Generally, the bias
1069 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
1070 those from %timeit."""
1074 those from %timeit."""
1071
1075
1072 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
1076 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
1073 posix=False, strict=False)
1077 posix=False, strict=False)
1074 if stmt == "" and cell is None:
1078 if stmt == "" and cell is None:
1075 return
1079 return
1076
1080
1077 timefunc = timeit.default_timer
1081 timefunc = timeit.default_timer
1078 number = int(getattr(opts, "n", 0))
1082 number = int(getattr(opts, "n", 0))
1079 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
1080 repeat = int(getattr(opts, "r", default_repeat))
1084 repeat = int(getattr(opts, "r", default_repeat))
1081 precision = int(getattr(opts, "p", 3))
1085 precision = int(getattr(opts, "p", 3))
1082 quiet = 'q' in opts
1086 quiet = 'q' in opts
1083 return_result = 'o' in opts
1087 return_result = 'o' in opts
1084 if hasattr(opts, "t"):
1088 if hasattr(opts, "t"):
1085 timefunc = time.time
1089 timefunc = time.time
1086 if hasattr(opts, "c"):
1090 if hasattr(opts, "c"):
1087 timefunc = clock
1091 timefunc = clock
1088
1092
1089 timer = Timer(timer=timefunc)
1093 timer = Timer(timer=timefunc)
1090 # 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,
1091 # 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
1092 # to the shell namespace?
1096 # to the shell namespace?
1093 transform = self.shell.transform_cell
1097 transform = self.shell.transform_cell
1094
1098
1095 if cell is None:
1099 if cell is None:
1096 # called as line magic
1100 # called as line magic
1097 ast_setup = self.shell.compile.ast_parse("pass")
1101 ast_setup = self.shell.compile.ast_parse("pass")
1098 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1102 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1099 else:
1103 else:
1100 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1104 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1101 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1105 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1102
1106
1103 ast_setup = self.shell.transform_ast(ast_setup)
1107 ast_setup = self.shell.transform_ast(ast_setup)
1104 ast_stmt = self.shell.transform_ast(ast_stmt)
1108 ast_stmt = self.shell.transform_ast(ast_stmt)
1105
1109
1106 # 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
1107 # Invalid code may become valid when put inside the function & loop,
1111 # Invalid code may become valid when put inside the function & loop,
1108 # which messes up error messages.
1112 # which messes up error messages.
1109 # https://github.com/ipython/ipython/issues/10636
1113 # https://github.com/ipython/ipython/issues/10636
1110 self.shell.compile(ast_setup, "<magic-timeit-setup>", "exec")
1114 self.shell.compile(ast_setup, "<magic-timeit-setup>", "exec")
1111 self.shell.compile(ast_stmt, "<magic-timeit-stmt>", "exec")
1115 self.shell.compile(ast_stmt, "<magic-timeit-stmt>", "exec")
1112
1116
1113 # 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
1114 # 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
1115 # without affecting the timing code.
1119 # without affecting the timing code.
1116 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1120 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1117 ' setup\n'
1121 ' setup\n'
1118 ' _t0 = _timer()\n'
1122 ' _t0 = _timer()\n'
1119 ' for _i in _it:\n'
1123 ' for _i in _it:\n'
1120 ' stmt\n'
1124 ' stmt\n'
1121 ' _t1 = _timer()\n'
1125 ' _t1 = _timer()\n'
1122 ' return _t1 - _t0\n')
1126 ' return _t1 - _t0\n')
1123
1127
1124 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1128 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1125 timeit_ast = ast.fix_missing_locations(timeit_ast)
1129 timeit_ast = ast.fix_missing_locations(timeit_ast)
1126
1130
1127 # Track compilation time so it can be reported if too long
1131 # Track compilation time so it can be reported if too long
1128 # Minimum time above which compilation time will be reported
1132 # Minimum time above which compilation time will be reported
1129 tc_min = 0.1
1133 tc_min = 0.1
1130
1134
1131 t0 = clock()
1135 t0 = clock()
1132 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1136 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1133 tc = clock()-t0
1137 tc = clock()-t0
1134
1138
1135 ns = {}
1139 ns = {}
1136 glob = self.shell.user_ns
1140 glob = self.shell.user_ns
1137 # 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.
1138 conflict_globs = {}
1142 conflict_globs = {}
1139 if local_ns and cell is None:
1143 if local_ns and cell is None:
1140 for var_name, var_val in glob.items():
1144 for var_name, var_val in glob.items():
1141 if var_name in local_ns:
1145 if var_name in local_ns:
1142 conflict_globs[var_name] = var_val
1146 conflict_globs[var_name] = var_val
1143 glob.update(local_ns)
1147 glob.update(local_ns)
1144
1148
1145 exec(code, glob, ns)
1149 exec(code, glob, ns)
1146 timer.inner = ns["inner"]
1150 timer.inner = ns["inner"]
1147
1151
1148 # 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
1149 # best and worst timings.
1153 # best and worst timings.
1150 # Issue: https://github.com/ipython/ipython/issues/6471
1154 # Issue: https://github.com/ipython/ipython/issues/6471
1151 if number == 0:
1155 if number == 0:
1152 # determine number so that 0.2 <= total time < 2.0
1156 # determine number so that 0.2 <= total time < 2.0
1153 for index in range(0, 10):
1157 for index in range(0, 10):
1154 number = 10 ** index
1158 number = 10 ** index
1155 time_number = timer.timeit(number)
1159 time_number = timer.timeit(number)
1156 if time_number >= 0.2:
1160 if time_number >= 0.2:
1157 break
1161 break
1158
1162
1159 all_runs = timer.repeat(repeat, number)
1163 all_runs = timer.repeat(repeat, number)
1160 best = min(all_runs) / number
1164 best = min(all_runs) / number
1161 worst = max(all_runs) / number
1165 worst = max(all_runs) / number
1162 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1166 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1163
1167
1164 # Restore global vars from conflict_globs
1168 # Restore global vars from conflict_globs
1165 if conflict_globs:
1169 if conflict_globs:
1166 glob.update(conflict_globs)
1170 glob.update(conflict_globs)
1167
1171
1168 if not quiet :
1172 if not quiet :
1169 # Check best timing is greater than zero to avoid a
1173 # Check best timing is greater than zero to avoid a
1170 # ZeroDivisionError.
1174 # ZeroDivisionError.
1171 # In cases where the slowest timing is lesser than a microsecond
1175 # In cases where the slowest timing is lesser than a microsecond
1172 # we assume that it does not really matter if the fastest
1176 # we assume that it does not really matter if the fastest
1173 # timing is 4 times faster than the slowest timing or not.
1177 # timing is 4 times faster than the slowest timing or not.
1174 if worst > 4 * best and best > 0 and worst > 1e-6:
1178 if worst > 4 * best and best > 0 and worst > 1e-6:
1175 print("The slowest run took %0.2f times longer than the "
1179 print("The slowest run took %0.2f times longer than the "
1176 "fastest. This could mean that an intermediate result "
1180 "fastest. This could mean that an intermediate result "
1177 "is being cached." % (worst / best))
1181 "is being cached." % (worst / best))
1178
1182
1179 print( timeit_result )
1183 print( timeit_result )
1180
1184
1181 if tc > tc_min:
1185 if tc > tc_min:
1182 print("Compiler time: %.2f s" % tc)
1186 print("Compiler time: %.2f s" % tc)
1183 if return_result:
1187 if return_result:
1184 return timeit_result
1188 return timeit_result
1185
1189
1186 @skip_doctest
1190 @skip_doctest
1187 @no_var_expand
1191 @no_var_expand
1188 @needs_local_scope
1192 @needs_local_scope
1189 @line_cell_magic
1193 @line_cell_magic
1190 def time(self,line='', cell=None, local_ns=None):
1194 def time(self,line='', cell=None, local_ns=None):
1191 """Time execution of a Python statement or expression.
1195 """Time execution of a Python statement or expression.
1192
1196
1193 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
1194 expression (if any) is returned. Note that under Win32, system time
1198 expression (if any) is returned. Note that under Win32, system time
1195 is always reported as 0, since it can not be measured.
1199 is always reported as 0, since it can not be measured.
1196
1200
1197 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:
1198
1202
1199 - 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
1200 ones can be chained with using semicolons).
1204 ones can be chained with using semicolons).
1201
1205
1202 - In cell mode, you can time the cell body (a directly
1206 - In cell mode, you can time the cell body (a directly
1203 following statement raises an error).
1207 following statement raises an error).
1204
1208
1205 This function provides very basic timing functionality. Use the timeit
1209 This function provides very basic timing functionality. Use the timeit
1206 magic for more control over the measurement.
1210 magic for more control over the measurement.
1207
1211
1208 .. versionchanged:: 7.3
1212 .. versionchanged:: 7.3
1209 User variables are no longer expanded,
1213 User variables are no longer expanded,
1210 the magic line is always left unmodified.
1214 the magic line is always left unmodified.
1211
1215
1212 Examples
1216 Examples
1213 --------
1217 --------
1214 ::
1218 ::
1215
1219
1216 In [1]: %time 2**128
1220 In [1]: %time 2**128
1217 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
1218 Wall time: 0.00
1222 Wall time: 0.00
1219 Out[1]: 340282366920938463463374607431768211456L
1223 Out[1]: 340282366920938463463374607431768211456L
1220
1224
1221 In [2]: n = 1000000
1225 In [2]: n = 1000000
1222
1226
1223 In [3]: %time sum(range(n))
1227 In [3]: %time sum(range(n))
1224 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
1225 Wall time: 1.37
1229 Wall time: 1.37
1226 Out[3]: 499999500000L
1230 Out[3]: 499999500000L
1227
1231
1228 In [4]: %time print 'hello world'
1232 In [4]: %time print 'hello world'
1229 hello world
1233 hello world
1230 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
1231 Wall time: 0.00
1235 Wall time: 0.00
1232
1236
1233 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
1234 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
1235 actual exponentiation is done by Python at compilation time, so while
1239 actual exponentiation is done by Python at compilation time, so while
1236 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
1237 time is purely due to the compilation:
1241 time is purely due to the compilation:
1238
1242
1239 In [5]: %time 3**9999;
1243 In [5]: %time 3**9999;
1240 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
1241 Wall time: 0.00 s
1245 Wall time: 0.00 s
1242
1246
1243 In [6]: %time 3**999999;
1247 In [6]: %time 3**999999;
1244 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
1245 Wall time: 0.00 s
1249 Wall time: 0.00 s
1246 Compiler : 0.78 s
1250 Compiler : 0.78 s
1247 """
1251 """
1248
1252
1249 # fail immediately if the given expression can't be compiled
1253 # fail immediately if the given expression can't be compiled
1250
1254
1251 if line and cell:
1255 if line and cell:
1252 raise UsageError("Can't use statement directly after '%%time'!")
1256 raise UsageError("Can't use statement directly after '%%time'!")
1253
1257
1254 if cell:
1258 if cell:
1255 expr = self.shell.transform_cell(cell)
1259 expr = self.shell.transform_cell(cell)
1256 else:
1260 else:
1257 expr = self.shell.transform_cell(line)
1261 expr = self.shell.transform_cell(line)
1258
1262
1259 # Minimum time above which parse time will be reported
1263 # Minimum time above which parse time will be reported
1260 tp_min = 0.1
1264 tp_min = 0.1
1261
1265
1262 t0 = clock()
1266 t0 = clock()
1263 expr_ast = self.shell.compile.ast_parse(expr)
1267 expr_ast = self.shell.compile.ast_parse(expr)
1264 tp = clock()-t0
1268 tp = clock()-t0
1265
1269
1266 # Apply AST transformations
1270 # Apply AST transformations
1267 expr_ast = self.shell.transform_ast(expr_ast)
1271 expr_ast = self.shell.transform_ast(expr_ast)
1268
1272
1269 # Minimum time above which compilation time will be reported
1273 # Minimum time above which compilation time will be reported
1270 tc_min = 0.1
1274 tc_min = 0.1
1271
1275
1272 expr_val=None
1276 expr_val=None
1273 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):
1274 mode = 'eval'
1278 mode = 'eval'
1275 source = '<timed eval>'
1279 source = '<timed eval>'
1276 expr_ast = ast.Expression(expr_ast.body[0].value)
1280 expr_ast = ast.Expression(expr_ast.body[0].value)
1277 else:
1281 else:
1278 mode = 'exec'
1282 mode = 'exec'
1279 source = '<timed exec>'
1283 source = '<timed exec>'
1280 # multi-line %%time case
1284 # multi-line %%time case
1281 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):
1282 expr_val= expr_ast.body[-1]
1286 expr_val= expr_ast.body[-1]
1283 expr_ast = expr_ast.body[:-1]
1287 expr_ast = expr_ast.body[:-1]
1284 expr_ast = Module(expr_ast, [])
1288 expr_ast = Module(expr_ast, [])
1285 expr_val = ast.Expression(expr_val.value)
1289 expr_val = ast.Expression(expr_val.value)
1286
1290
1287 t0 = clock()
1291 t0 = clock()
1288 code = self.shell.compile(expr_ast, source, mode)
1292 code = self.shell.compile(expr_ast, source, mode)
1289 tc = clock()-t0
1293 tc = clock()-t0
1290
1294
1291 # skew measurement as little as possible
1295 # skew measurement as little as possible
1292 glob = self.shell.user_ns
1296 glob = self.shell.user_ns
1293 wtime = time.time
1297 wtime = time.time
1294 # time execution
1298 # time execution
1295 wall_st = wtime()
1299 wall_st = wtime()
1296 if mode=='eval':
1300 if mode=='eval':
1297 st = clock2()
1301 st = clock2()
1298 try:
1302 try:
1299 out = eval(code, glob, local_ns)
1303 out = eval(code, glob, local_ns)
1300 except:
1304 except:
1301 self.shell.showtraceback()
1305 self.shell.showtraceback()
1302 return
1306 return
1303 end = clock2()
1307 end = clock2()
1304 else:
1308 else:
1305 st = clock2()
1309 st = clock2()
1306 try:
1310 try:
1307 exec(code, glob, local_ns)
1311 exec(code, glob, local_ns)
1308 out=None
1312 out=None
1309 # multi-line %%time case
1313 # multi-line %%time case
1310 if expr_val is not None:
1314 if expr_val is not None:
1311 code_2 = self.shell.compile(expr_val, source, 'eval')
1315 code_2 = self.shell.compile(expr_val, source, 'eval')
1312 out = eval(code_2, glob, local_ns)
1316 out = eval(code_2, glob, local_ns)
1313 except:
1317 except:
1314 self.shell.showtraceback()
1318 self.shell.showtraceback()
1315 return
1319 return
1316 end = clock2()
1320 end = clock2()
1317
1321
1318 wall_end = wtime()
1322 wall_end = wtime()
1319 # Compute actual times and report
1323 # Compute actual times and report
1320 wall_time = wall_end-wall_st
1324 wall_time = wall_end-wall_st
1321 cpu_user = end[0]-st[0]
1325 cpu_user = end[0]-st[0]
1322 cpu_sys = end[1]-st[1]
1326 cpu_sys = end[1]-st[1]
1323 cpu_tot = cpu_user+cpu_sys
1327 cpu_tot = cpu_user+cpu_sys
1324 # 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
1325 if sys.platform != 'win32':
1329 if sys.platform != 'win32':
1326 print("CPU times: user %s, sys: %s, total: %s" % \
1330 print("CPU times: user %s, sys: %s, total: %s" % \
1327 (_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)))
1328 print("Wall time: %s" % _format_time(wall_time))
1332 print("Wall time: %s" % _format_time(wall_time))
1329 if tc > tc_min:
1333 if tc > tc_min:
1330 print("Compiler : %s" % _format_time(tc))
1334 print("Compiler : %s" % _format_time(tc))
1331 if tp > tp_min:
1335 if tp > tp_min:
1332 print("Parser : %s" % _format_time(tp))
1336 print("Parser : %s" % _format_time(tp))
1333 return out
1337 return out
1334
1338
1335 @skip_doctest
1339 @skip_doctest
1336 @line_magic
1340 @line_magic
1337 def macro(self, parameter_s=''):
1341 def macro(self, parameter_s=''):
1338 """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,
1339 filenames or string objects.
1343 filenames or string objects.
1340
1344
1341 Usage:\\
1345 Usage:\\
1342 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1346 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1343
1347
1344 Options:
1348 Options:
1345
1349
1346 -r: use 'raw' input. By default, the 'processed' history is used,
1350 -r: use 'raw' input. By default, the 'processed' history is used,
1347 so that magics are loaded in their transformed version to valid
1351 so that magics are loaded in their transformed version to valid
1348 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
1349 command line is used instead.
1353 command line is used instead.
1350
1354
1351 -q: quiet macro definition. By default, a tag line is printed
1355 -q: quiet macro definition. By default, a tag line is printed
1352 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
1353 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
1354 is produced once the macro is created.
1358 is produced once the macro is created.
1355
1359
1356 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
1357 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
1358 above) from your input history into a single string. This variable
1362 above) from your input history into a single string. This variable
1359 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
1360 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
1361 executes.
1365 executes.
1362
1366
1363 The syntax for indicating input ranges is described in %history.
1367 The syntax for indicating input ranges is described in %history.
1364
1368
1365 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
1366 notation, where N:M means numbers N through M-1.
1370 notation, where N:M means numbers N through M-1.
1367
1371
1368 For example, if your history contains (print using %hist -n )::
1372 For example, if your history contains (print using %hist -n )::
1369
1373
1370 44: x=1
1374 44: x=1
1371 45: y=3
1375 45: y=3
1372 46: z=x+y
1376 46: z=x+y
1373 47: print x
1377 47: print x
1374 48: a=5
1378 48: a=5
1375 49: print 'x',x,'y',y
1379 49: print 'x',x,'y',y
1376
1380
1377 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
1378 called my_macro with::
1382 called my_macro with::
1379
1383
1380 In [55]: %macro my_macro 44-47 49
1384 In [55]: %macro my_macro 44-47 49
1381
1385
1382 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
1383 in one pass.
1387 in one pass.
1384
1388
1385 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
1386 number can appear multiple times. You can assemble macros with any
1390 number can appear multiple times. You can assemble macros with any
1387 lines from your input history in any order.
1391 lines from your input history in any order.
1388
1392
1389 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,
1390 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
1391 code instead of printing them when you type their name.
1395 code instead of printing them when you type their name.
1392
1396
1393 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::
1394
1398
1395 print macro_name
1399 print macro_name
1396
1400
1397 """
1401 """
1398 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1402 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1399 if not args: # List existing macros
1403 if not args: # List existing macros
1400 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))
1401 if len(args) == 1:
1405 if len(args) == 1:
1402 raise UsageError(
1406 raise UsageError(
1403 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1407 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1404 name, codefrom = args[0], " ".join(args[1:])
1408 name, codefrom = args[0], " ".join(args[1:])
1405
1409
1406 #print 'rng',ranges # dbg
1410 #print 'rng',ranges # dbg
1407 try:
1411 try:
1408 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1412 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1409 except (ValueError, TypeError) as e:
1413 except (ValueError, TypeError) as e:
1410 print(e.args[0])
1414 print(e.args[0])
1411 return
1415 return
1412 macro = Macro(lines)
1416 macro = Macro(lines)
1413 self.shell.define_macro(name, macro)
1417 self.shell.define_macro(name, macro)
1414 if not ( 'q' in opts) :
1418 if not ( 'q' in opts) :
1415 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)
1416 print('=== Macro contents: ===')
1420 print('=== Macro contents: ===')
1417 print(macro, end=' ')
1421 print(macro, end=' ')
1418
1422
1419 @magic_arguments.magic_arguments()
1423 @magic_arguments.magic_arguments()
1420 @magic_arguments.argument('output', type=str, default='', nargs='?',
1424 @magic_arguments.argument('output', type=str, default='', nargs='?',
1421 help="""The name of the variable in which to store output.
1425 help="""The name of the variable in which to store output.
1422 This is a utils.io.CapturedIO object with stdout/err attributes
1426 This is a utils.io.CapturedIO object with stdout/err attributes
1423 for the text of the captured output.
1427 for the text of the captured output.
1424
1428
1425 CapturedOutput also has a show() method for displaying the output,
1429 CapturedOutput also has a show() method for displaying the output,
1426 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
1427 output.
1431 output.
1428
1432
1429 If unspecified, captured output is discarded.
1433 If unspecified, captured output is discarded.
1430 """
1434 """
1431 )
1435 )
1432 @magic_arguments.argument('--no-stderr', action="store_true",
1436 @magic_arguments.argument('--no-stderr', action="store_true",
1433 help="""Don't capture stderr."""
1437 help="""Don't capture stderr."""
1434 )
1438 )
1435 @magic_arguments.argument('--no-stdout', action="store_true",
1439 @magic_arguments.argument('--no-stdout', action="store_true",
1436 help="""Don't capture stdout."""
1440 help="""Don't capture stdout."""
1437 )
1441 )
1438 @magic_arguments.argument('--no-display', action="store_true",
1442 @magic_arguments.argument('--no-display', action="store_true",
1439 help="""Don't capture IPython's rich display."""
1443 help="""Don't capture IPython's rich display."""
1440 )
1444 )
1441 @cell_magic
1445 @cell_magic
1442 def capture(self, line, cell):
1446 def capture(self, line, cell):
1443 """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."""
1444 args = magic_arguments.parse_argstring(self.capture, line)
1448 args = magic_arguments.parse_argstring(self.capture, line)
1445 out = not args.no_stdout
1449 out = not args.no_stdout
1446 err = not args.no_stderr
1450 err = not args.no_stderr
1447 disp = not args.no_display
1451 disp = not args.no_display
1448 with capture_output(out, err, disp) as io:
1452 with capture_output(out, err, disp) as io:
1449 self.shell.run_cell(cell)
1453 self.shell.run_cell(cell)
1450 if args.output:
1454 if args.output:
1451 self.shell.user_ns[args.output] = io
1455 self.shell.user_ns[args.output] = io
1452
1456
1453 def parse_breakpoint(text, current_file):
1457 def parse_breakpoint(text, current_file):
1454 '''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'''
1455 colon = text.find(':')
1459 colon = text.find(':')
1456 if colon == -1:
1460 if colon == -1:
1457 return current_file, int(text)
1461 return current_file, int(text)
1458 else:
1462 else:
1459 return text[:colon], int(text[colon+1:])
1463 return text[:colon], int(text[colon+1:])
1460
1464
1461 def _format_time(timespan, precision=3):
1465 def _format_time(timespan, precision=3):
1462 """Formats the timespan in a human readable form"""
1466 """Formats the timespan in a human readable form"""
1463
1467
1464 if timespan >= 60.0:
1468 if timespan >= 60.0:
1465 # 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
1466 # Idea from http://snipplr.com/view/5713/
1470 # Idea from http://snipplr.com/view/5713/
1467 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)]
1468 time = []
1472 time = []
1469 leftover = timespan
1473 leftover = timespan
1470 for suffix, length in parts:
1474 for suffix, length in parts:
1471 value = int(leftover / length)
1475 value = int(leftover / length)
1472 if value > 0:
1476 if value > 0:
1473 leftover = leftover % length
1477 leftover = leftover % length
1474 time.append(u'%s%s' % (str(value), suffix))
1478 time.append(u'%s%s' % (str(value), suffix))
1475 if leftover < 1:
1479 if leftover < 1:
1476 break
1480 break
1477 return " ".join(time)
1481 return " ".join(time)
1478
1482
1479
1483
1480 # Unfortunately the unicode 'micro' symbol can cause problems in
1484 # Unfortunately the unicode 'micro' symbol can cause problems in
1481 # certain terminals.
1485 # certain terminals.
1482 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1486 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1483 # 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
1484 # 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.
1485 units = [u"s", u"ms",u'us',"ns"] # the save value
1489 units = [u"s", u"ms",u'us',"ns"] # the save value
1486 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1490 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1487 try:
1491 try:
1488 u'\xb5'.encode(sys.stdout.encoding)
1492 u'\xb5'.encode(sys.stdout.encoding)
1489 units = [u"s", u"ms",u'\xb5s',"ns"]
1493 units = [u"s", u"ms",u'\xb5s',"ns"]
1490 except:
1494 except:
1491 pass
1495 pass
1492 scaling = [1, 1e3, 1e6, 1e9]
1496 scaling = [1, 1e3, 1e6, 1e9]
1493
1497
1494 if timespan > 0.0:
1498 if timespan > 0.0:
1495 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1499 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1496 else:
1500 else:
1497 order = 3
1501 order = 3
1498 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