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