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