##// END OF EJS Templates
Remove PY3 variable
Srinivas Reddy Thatiparthy -
Show More
@@ -1,1380 +1,1374 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 gc
10 import gc
11 import itertools
11 import itertools
12 import os
12 import os
13 import sys
13 import sys
14 import time
14 import time
15 import timeit
15 import timeit
16 import math
16 import math
17 from pdb import Restart
17 from pdb import Restart
18
18
19 # cProfile was added in Python2.5
19 # cProfile was added in Python2.5
20 try:
20 try:
21 import cProfile as profile
21 import cProfile as profile
22 import pstats
22 import pstats
23 except ImportError:
23 except ImportError:
24 # profile isn't bundled by default in Debian for license reasons
24 # profile isn't bundled by default in Debian for license reasons
25 try:
25 try:
26 import profile, pstats
26 import profile, pstats
27 except ImportError:
27 except ImportError:
28 profile = pstats = None
28 profile = pstats = None
29
29
30 from IPython.core import oinspect
30 from IPython.core import oinspect
31 from IPython.core import magic_arguments
31 from IPython.core import magic_arguments
32 from IPython.core import page
32 from IPython.core import page
33 from IPython.core.error import UsageError
33 from IPython.core.error import UsageError
34 from IPython.core.macro import Macro
34 from IPython.core.macro import Macro
35 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
35 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
36 line_cell_magic, on_off, needs_local_scope)
36 line_cell_magic, on_off, needs_local_scope)
37 from IPython.testing.skipdoctest import skip_doctest
37 from IPython.testing.skipdoctest import skip_doctest
38 from IPython.utils import py3compat
38 from IPython.utils import py3compat
39 from IPython.utils.py3compat import builtin_mod, PY3
39 from IPython.utils.py3compat import builtin_mod
40 from IPython.utils.contexts import preserve_keys
40 from IPython.utils.contexts import preserve_keys
41 from IPython.utils.capture import capture_output
41 from IPython.utils.capture import capture_output
42 from IPython.utils.ipstruct import Struct
42 from IPython.utils.ipstruct import Struct
43 from IPython.utils.module_paths import find_mod
43 from IPython.utils.module_paths import find_mod
44 from IPython.utils.path import get_py_filename, shellglob
44 from IPython.utils.path import get_py_filename, shellglob
45 from IPython.utils.timing import clock, clock2
45 from IPython.utils.timing import clock, clock2
46 from warnings import warn
46 from warnings import warn
47 from logging import error
47 from logging import error
48 from io import StringIO
48
49
49 if PY3:
50 from io import StringIO
51 else:
52 from StringIO import StringIO
53
50
54 #-----------------------------------------------------------------------------
51 #-----------------------------------------------------------------------------
55 # Magic implementation classes
52 # Magic implementation classes
56 #-----------------------------------------------------------------------------
53 #-----------------------------------------------------------------------------
57
54
58
55
59 class TimeitResult(object):
56 class TimeitResult(object):
60 """
57 """
61 Object returned by the timeit magic with info about the run.
58 Object returned by the timeit magic with info about the run.
62
59
63 Contains the following attributes :
60 Contains the following attributes :
64
61
65 loops: (int) number of loops done per measurement
62 loops: (int) number of loops done per measurement
66 repeat: (int) number of times the measurement has been repeated
63 repeat: (int) number of times the measurement has been repeated
67 best: (float) best execution time / number
64 best: (float) best execution time / number
68 all_runs: (list of float) execution time of each run (in s)
65 all_runs: (list of float) execution time of each run (in s)
69 compile_time: (float) time of statement compilation (s)
66 compile_time: (float) time of statement compilation (s)
70
67
71 """
68 """
72 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
69 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
73 self.loops = loops
70 self.loops = loops
74 self.repeat = repeat
71 self.repeat = repeat
75 self.best = best
72 self.best = best
76 self.worst = worst
73 self.worst = worst
77 self.all_runs = all_runs
74 self.all_runs = all_runs
78 self.compile_time = compile_time
75 self.compile_time = compile_time
79 self._precision = precision
76 self._precision = precision
80 self.timings = [ dt / self.loops for dt in all_runs]
77 self.timings = [ dt / self.loops for dt in all_runs]
81
78
82 @property
79 @property
83 def average(self):
80 def average(self):
84 return math.fsum(self.timings) / len(self.timings)
81 return math.fsum(self.timings) / len(self.timings)
85
82
86 @property
83 @property
87 def stdev(self):
84 def stdev(self):
88 mean = self.average
85 mean = self.average
89 return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5
86 return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5
90
87
91 def __str__(self):
88 def __str__(self):
92 return (u"%s loop%s, average of %d: %s +- %s per loop (using standard deviation)"
89 return (u"%s loop%s, average of %d: %s +- %s per loop (using standard deviation)"
93 % (self.loops,"" if self.loops == 1 else "s", self.repeat,
90 % (self.loops,"" if self.loops == 1 else "s", self.repeat,
94 _format_time(self.average, self._precision),
91 _format_time(self.average, self._precision),
95 _format_time(self.stdev, self._precision)))
92 _format_time(self.stdev, self._precision)))
96
93
97 def _repr_pretty_(self, p , cycle):
94 def _repr_pretty_(self, p , cycle):
98 unic = self.__str__()
95 unic = self.__str__()
99 p.text(u'<TimeitResult : '+unic+u'>')
96 p.text(u'<TimeitResult : '+unic+u'>')
100
97
101
98
102
99
103 class TimeitTemplateFiller(ast.NodeTransformer):
100 class TimeitTemplateFiller(ast.NodeTransformer):
104 """Fill in the AST template for timing execution.
101 """Fill in the AST template for timing execution.
105
102
106 This is quite closely tied to the template definition, which is in
103 This is quite closely tied to the template definition, which is in
107 :meth:`ExecutionMagics.timeit`.
104 :meth:`ExecutionMagics.timeit`.
108 """
105 """
109 def __init__(self, ast_setup, ast_stmt):
106 def __init__(self, ast_setup, ast_stmt):
110 self.ast_setup = ast_setup
107 self.ast_setup = ast_setup
111 self.ast_stmt = ast_stmt
108 self.ast_stmt = ast_stmt
112
109
113 def visit_FunctionDef(self, node):
110 def visit_FunctionDef(self, node):
114 "Fill in the setup statement"
111 "Fill in the setup statement"
115 self.generic_visit(node)
112 self.generic_visit(node)
116 if node.name == "inner":
113 if node.name == "inner":
117 node.body[:1] = self.ast_setup.body
114 node.body[:1] = self.ast_setup.body
118
115
119 return node
116 return node
120
117
121 def visit_For(self, node):
118 def visit_For(self, node):
122 "Fill in the statement to be timed"
119 "Fill in the statement to be timed"
123 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
120 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
124 node.body = self.ast_stmt.body
121 node.body = self.ast_stmt.body
125 return node
122 return node
126
123
127
124
128 class Timer(timeit.Timer):
125 class Timer(timeit.Timer):
129 """Timer class that explicitly uses self.inner
126 """Timer class that explicitly uses self.inner
130
127
131 which is an undocumented implementation detail of CPython,
128 which is an undocumented implementation detail of CPython,
132 not shared by PyPy.
129 not shared by PyPy.
133 """
130 """
134 # Timer.timeit copied from CPython 3.4.2
131 # Timer.timeit copied from CPython 3.4.2
135 def timeit(self, number=timeit.default_number):
132 def timeit(self, number=timeit.default_number):
136 """Time 'number' executions of the main statement.
133 """Time 'number' executions of the main statement.
137
134
138 To be precise, this executes the setup statement once, and
135 To be precise, this executes the setup statement once, and
139 then returns the time it takes to execute the main statement
136 then returns the time it takes to execute the main statement
140 a number of times, as a float measured in seconds. The
137 a number of times, as a float measured in seconds. The
141 argument is the number of times through the loop, defaulting
138 argument is the number of times through the loop, defaulting
142 to one million. The main statement, the setup statement and
139 to one million. The main statement, the setup statement and
143 the timer function to be used are passed to the constructor.
140 the timer function to be used are passed to the constructor.
144 """
141 """
145 it = itertools.repeat(None, number)
142 it = itertools.repeat(None, number)
146 gcold = gc.isenabled()
143 gcold = gc.isenabled()
147 gc.disable()
144 gc.disable()
148 try:
145 try:
149 timing = self.inner(it, self.timer)
146 timing = self.inner(it, self.timer)
150 finally:
147 finally:
151 if gcold:
148 if gcold:
152 gc.enable()
149 gc.enable()
153 return timing
150 return timing
154
151
155
152
156 @magics_class
153 @magics_class
157 class ExecutionMagics(Magics):
154 class ExecutionMagics(Magics):
158 """Magics related to code execution, debugging, profiling, etc.
155 """Magics related to code execution, debugging, profiling, etc.
159
156
160 """
157 """
161
158
162 def __init__(self, shell):
159 def __init__(self, shell):
163 super(ExecutionMagics, self).__init__(shell)
160 super(ExecutionMagics, self).__init__(shell)
164 if profile is None:
161 if profile is None:
165 self.prun = self.profile_missing_notice
162 self.prun = self.profile_missing_notice
166 # Default execution function used to actually run user code.
163 # Default execution function used to actually run user code.
167 self.default_runner = None
164 self.default_runner = None
168
165
169 def profile_missing_notice(self, *args, **kwargs):
166 def profile_missing_notice(self, *args, **kwargs):
170 error("""\
167 error("""\
171 The profile module could not be found. It has been removed from the standard
168 The profile module could not be found. It has been removed from the standard
172 python packages because of its non-free license. To use profiling, install the
169 python packages because of its non-free license. To use profiling, install the
173 python-profiler package from non-free.""")
170 python-profiler package from non-free.""")
174
171
175 @skip_doctest
172 @skip_doctest
176 @line_cell_magic
173 @line_cell_magic
177 def prun(self, parameter_s='', cell=None):
174 def prun(self, parameter_s='', cell=None):
178
175
179 """Run a statement through the python code profiler.
176 """Run a statement through the python code profiler.
180
177
181 Usage, in line mode:
178 Usage, in line mode:
182 %prun [options] statement
179 %prun [options] statement
183
180
184 Usage, in cell mode:
181 Usage, in cell mode:
185 %%prun [options] [statement]
182 %%prun [options] [statement]
186 code...
183 code...
187 code...
184 code...
188
185
189 In cell mode, the additional code lines are appended to the (possibly
186 In cell mode, the additional code lines are appended to the (possibly
190 empty) statement in the first line. Cell mode allows you to easily
187 empty) statement in the first line. Cell mode allows you to easily
191 profile multiline blocks without having to put them in a separate
188 profile multiline blocks without having to put them in a separate
192 function.
189 function.
193
190
194 The given statement (which doesn't require quote marks) is run via the
191 The given statement (which doesn't require quote marks) is run via the
195 python profiler in a manner similar to the profile.run() function.
192 python profiler in a manner similar to the profile.run() function.
196 Namespaces are internally managed to work correctly; profile.run
193 Namespaces are internally managed to work correctly; profile.run
197 cannot be used in IPython because it makes certain assumptions about
194 cannot be used in IPython because it makes certain assumptions about
198 namespaces which do not hold under IPython.
195 namespaces which do not hold under IPython.
199
196
200 Options:
197 Options:
201
198
202 -l <limit>
199 -l <limit>
203 you can place restrictions on what or how much of the
200 you can place restrictions on what or how much of the
204 profile gets printed. The limit value can be:
201 profile gets printed. The limit value can be:
205
202
206 * A string: only information for function names containing this string
203 * A string: only information for function names containing this string
207 is printed.
204 is printed.
208
205
209 * An integer: only these many lines are printed.
206 * An integer: only these many lines are printed.
210
207
211 * A float (between 0 and 1): this fraction of the report is printed
208 * A float (between 0 and 1): this fraction of the report is printed
212 (for example, use a limit of 0.4 to see the topmost 40% only).
209 (for example, use a limit of 0.4 to see the topmost 40% only).
213
210
214 You can combine several limits with repeated use of the option. For
211 You can combine several limits with repeated use of the option. For
215 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
212 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
216 information about class constructors.
213 information about class constructors.
217
214
218 -r
215 -r
219 return the pstats.Stats object generated by the profiling. This
216 return the pstats.Stats object generated by the profiling. This
220 object has all the information about the profile in it, and you can
217 object has all the information about the profile in it, and you can
221 later use it for further analysis or in other functions.
218 later use it for further analysis or in other functions.
222
219
223 -s <key>
220 -s <key>
224 sort profile by given key. You can provide more than one key
221 sort profile by given key. You can provide more than one key
225 by using the option several times: '-s key1 -s key2 -s key3...'. The
222 by using the option several times: '-s key1 -s key2 -s key3...'. The
226 default sorting key is 'time'.
223 default sorting key is 'time'.
227
224
228 The following is copied verbatim from the profile documentation
225 The following is copied verbatim from the profile documentation
229 referenced below:
226 referenced below:
230
227
231 When more than one key is provided, additional keys are used as
228 When more than one key is provided, additional keys are used as
232 secondary criteria when the there is equality in all keys selected
229 secondary criteria when the there is equality in all keys selected
233 before them.
230 before them.
234
231
235 Abbreviations can be used for any key names, as long as the
232 Abbreviations can be used for any key names, as long as the
236 abbreviation is unambiguous. The following are the keys currently
233 abbreviation is unambiguous. The following are the keys currently
237 defined:
234 defined:
238
235
239 ============ =====================
236 ============ =====================
240 Valid Arg Meaning
237 Valid Arg Meaning
241 ============ =====================
238 ============ =====================
242 "calls" call count
239 "calls" call count
243 "cumulative" cumulative time
240 "cumulative" cumulative time
244 "file" file name
241 "file" file name
245 "module" file name
242 "module" file name
246 "pcalls" primitive call count
243 "pcalls" primitive call count
247 "line" line number
244 "line" line number
248 "name" function name
245 "name" function name
249 "nfl" name/file/line
246 "nfl" name/file/line
250 "stdname" standard name
247 "stdname" standard name
251 "time" internal time
248 "time" internal time
252 ============ =====================
249 ============ =====================
253
250
254 Note that all sorts on statistics are in descending order (placing
251 Note that all sorts on statistics are in descending order (placing
255 most time consuming items first), where as name, file, and line number
252 most time consuming items first), where as name, file, and line number
256 searches are in ascending order (i.e., alphabetical). The subtle
253 searches are in ascending order (i.e., alphabetical). The subtle
257 distinction between "nfl" and "stdname" is that the standard name is a
254 distinction between "nfl" and "stdname" is that the standard name is a
258 sort of the name as printed, which means that the embedded line
255 sort of the name as printed, which means that the embedded line
259 numbers get compared in an odd way. For example, lines 3, 20, and 40
256 numbers get compared in an odd way. For example, lines 3, 20, and 40
260 would (if the file names were the same) appear in the string order
257 would (if the file names were the same) appear in the string order
261 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
258 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
262 line numbers. In fact, sort_stats("nfl") is the same as
259 line numbers. In fact, sort_stats("nfl") is the same as
263 sort_stats("name", "file", "line").
260 sort_stats("name", "file", "line").
264
261
265 -T <filename>
262 -T <filename>
266 save profile results as shown on screen to a text
263 save profile results as shown on screen to a text
267 file. The profile is still shown on screen.
264 file. The profile is still shown on screen.
268
265
269 -D <filename>
266 -D <filename>
270 save (via dump_stats) profile statistics to given
267 save (via dump_stats) profile statistics to given
271 filename. This data is in a format understood by the pstats module, and
268 filename. This data is in a format understood by the pstats module, and
272 is generated by a call to the dump_stats() method of profile
269 is generated by a call to the dump_stats() method of profile
273 objects. The profile is still shown on screen.
270 objects. The profile is still shown on screen.
274
271
275 -q
272 -q
276 suppress output to the pager. Best used with -T and/or -D above.
273 suppress output to the pager. Best used with -T and/or -D above.
277
274
278 If you want to run complete programs under the profiler's control, use
275 If you want to run complete programs under the profiler's control, use
279 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
276 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
280 contains profiler specific options as described here.
277 contains profiler specific options as described here.
281
278
282 You can read the complete documentation for the profile module with::
279 You can read the complete documentation for the profile module with::
283
280
284 In [1]: import profile; profile.help()
281 In [1]: import profile; profile.help()
285 """
282 """
286 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
283 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
287 list_all=True, posix=False)
284 list_all=True, posix=False)
288 if cell is not None:
285 if cell is not None:
289 arg_str += '\n' + cell
286 arg_str += '\n' + cell
290 arg_str = self.shell.input_splitter.transform_cell(arg_str)
287 arg_str = self.shell.input_splitter.transform_cell(arg_str)
291 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
288 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
292
289
293 def _run_with_profiler(self, code, opts, namespace):
290 def _run_with_profiler(self, code, opts, namespace):
294 """
291 """
295 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
292 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
296
293
297 Parameters
294 Parameters
298 ----------
295 ----------
299 code : str
296 code : str
300 Code to be executed.
297 Code to be executed.
301 opts : Struct
298 opts : Struct
302 Options parsed by `self.parse_options`.
299 Options parsed by `self.parse_options`.
303 namespace : dict
300 namespace : dict
304 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
301 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
305
302
306 """
303 """
307
304
308 # Fill default values for unspecified options:
305 # Fill default values for unspecified options:
309 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
306 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
310
307
311 prof = profile.Profile()
308 prof = profile.Profile()
312 try:
309 try:
313 prof = prof.runctx(code, namespace, namespace)
310 prof = prof.runctx(code, namespace, namespace)
314 sys_exit = ''
311 sys_exit = ''
315 except SystemExit:
312 except SystemExit:
316 sys_exit = """*** SystemExit exception caught in code being profiled."""
313 sys_exit = """*** SystemExit exception caught in code being profiled."""
317
314
318 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
315 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
319
316
320 lims = opts.l
317 lims = opts.l
321 if lims:
318 if lims:
322 lims = [] # rebuild lims with ints/floats/strings
319 lims = [] # rebuild lims with ints/floats/strings
323 for lim in opts.l:
320 for lim in opts.l:
324 try:
321 try:
325 lims.append(int(lim))
322 lims.append(int(lim))
326 except ValueError:
323 except ValueError:
327 try:
324 try:
328 lims.append(float(lim))
325 lims.append(float(lim))
329 except ValueError:
326 except ValueError:
330 lims.append(lim)
327 lims.append(lim)
331
328
332 # Trap output.
329 # Trap output.
333 stdout_trap = StringIO()
330 stdout_trap = StringIO()
334 stats_stream = stats.stream
331 stats_stream = stats.stream
335 try:
332 try:
336 stats.stream = stdout_trap
333 stats.stream = stdout_trap
337 stats.print_stats(*lims)
334 stats.print_stats(*lims)
338 finally:
335 finally:
339 stats.stream = stats_stream
336 stats.stream = stats_stream
340
337
341 output = stdout_trap.getvalue()
338 output = stdout_trap.getvalue()
342 output = output.rstrip()
339 output = output.rstrip()
343
340
344 if 'q' not in opts:
341 if 'q' not in opts:
345 page.page(output)
342 page.page(output)
346 print(sys_exit, end=' ')
343 print(sys_exit, end=' ')
347
344
348 dump_file = opts.D[0]
345 dump_file = opts.D[0]
349 text_file = opts.T[0]
346 text_file = opts.T[0]
350 if dump_file:
347 if dump_file:
351 prof.dump_stats(dump_file)
348 prof.dump_stats(dump_file)
352 print('\n*** Profile stats marshalled to file',\
349 print('\n*** Profile stats marshalled to file',\
353 repr(dump_file)+'.',sys_exit)
350 repr(dump_file)+'.',sys_exit)
354 if text_file:
351 if text_file:
355 pfile = open(text_file,'w')
352 pfile = open(text_file,'w')
356 pfile.write(output)
353 pfile.write(output)
357 pfile.close()
354 pfile.close()
358 print('\n*** Profile printout saved to text file',\
355 print('\n*** Profile printout saved to text file',\
359 repr(text_file)+'.',sys_exit)
356 repr(text_file)+'.',sys_exit)
360
357
361 if 'r' in opts:
358 if 'r' in opts:
362 return stats
359 return stats
363 else:
360 else:
364 return None
361 return None
365
362
366 @line_magic
363 @line_magic
367 def pdb(self, parameter_s=''):
364 def pdb(self, parameter_s=''):
368 """Control the automatic calling of the pdb interactive debugger.
365 """Control the automatic calling of the pdb interactive debugger.
369
366
370 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
367 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
371 argument it works as a toggle.
368 argument it works as a toggle.
372
369
373 When an exception is triggered, IPython can optionally call the
370 When an exception is triggered, IPython can optionally call the
374 interactive pdb debugger after the traceback printout. %pdb toggles
371 interactive pdb debugger after the traceback printout. %pdb toggles
375 this feature on and off.
372 this feature on and off.
376
373
377 The initial state of this feature is set in your configuration
374 The initial state of this feature is set in your configuration
378 file (the option is ``InteractiveShell.pdb``).
375 file (the option is ``InteractiveShell.pdb``).
379
376
380 If you want to just activate the debugger AFTER an exception has fired,
377 If you want to just activate the debugger AFTER an exception has fired,
381 without having to type '%pdb on' and rerunning your code, you can use
378 without having to type '%pdb on' and rerunning your code, you can use
382 the %debug magic."""
379 the %debug magic."""
383
380
384 par = parameter_s.strip().lower()
381 par = parameter_s.strip().lower()
385
382
386 if par:
383 if par:
387 try:
384 try:
388 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
385 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
389 except KeyError:
386 except KeyError:
390 print ('Incorrect argument. Use on/1, off/0, '
387 print ('Incorrect argument. Use on/1, off/0, '
391 'or nothing for a toggle.')
388 'or nothing for a toggle.')
392 return
389 return
393 else:
390 else:
394 # toggle
391 # toggle
395 new_pdb = not self.shell.call_pdb
392 new_pdb = not self.shell.call_pdb
396
393
397 # set on the shell
394 # set on the shell
398 self.shell.call_pdb = new_pdb
395 self.shell.call_pdb = new_pdb
399 print('Automatic pdb calling has been turned',on_off(new_pdb))
396 print('Automatic pdb calling has been turned',on_off(new_pdb))
400
397
401 @skip_doctest
398 @skip_doctest
402 @magic_arguments.magic_arguments()
399 @magic_arguments.magic_arguments()
403 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
400 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
404 help="""
401 help="""
405 Set break point at LINE in FILE.
402 Set break point at LINE in FILE.
406 """
403 """
407 )
404 )
408 @magic_arguments.argument('statement', nargs='*',
405 @magic_arguments.argument('statement', nargs='*',
409 help="""
406 help="""
410 Code to run in debugger.
407 Code to run in debugger.
411 You can omit this in cell magic mode.
408 You can omit this in cell magic mode.
412 """
409 """
413 )
410 )
414 @line_cell_magic
411 @line_cell_magic
415 def debug(self, line='', cell=None):
412 def debug(self, line='', cell=None):
416 """Activate the interactive debugger.
413 """Activate the interactive debugger.
417
414
418 This magic command support two ways of activating debugger.
415 This magic command support two ways of activating debugger.
419 One is to activate debugger before executing code. This way, you
416 One is to activate debugger before executing code. This way, you
420 can set a break point, to step through the code from the point.
417 can set a break point, to step through the code from the point.
421 You can use this mode by giving statements to execute and optionally
418 You can use this mode by giving statements to execute and optionally
422 a breakpoint.
419 a breakpoint.
423
420
424 The other one is to activate debugger in post-mortem mode. You can
421 The other one is to activate debugger in post-mortem mode. You can
425 activate this mode simply running %debug without any argument.
422 activate this mode simply running %debug without any argument.
426 If an exception has just occurred, this lets you inspect its stack
423 If an exception has just occurred, this lets you inspect its stack
427 frames interactively. Note that this will always work only on the last
424 frames interactively. Note that this will always work only on the last
428 traceback that occurred, so you must call this quickly after an
425 traceback that occurred, so you must call this quickly after an
429 exception that you wish to inspect has fired, because if another one
426 exception that you wish to inspect has fired, because if another one
430 occurs, it clobbers the previous one.
427 occurs, it clobbers the previous one.
431
428
432 If you want IPython to automatically do this on every exception, see
429 If you want IPython to automatically do this on every exception, see
433 the %pdb magic for more details.
430 the %pdb magic for more details.
434 """
431 """
435 args = magic_arguments.parse_argstring(self.debug, line)
432 args = magic_arguments.parse_argstring(self.debug, line)
436
433
437 if not (args.breakpoint or args.statement or cell):
434 if not (args.breakpoint or args.statement or cell):
438 self._debug_post_mortem()
435 self._debug_post_mortem()
439 else:
436 else:
440 code = "\n".join(args.statement)
437 code = "\n".join(args.statement)
441 if cell:
438 if cell:
442 code += "\n" + cell
439 code += "\n" + cell
443 self._debug_exec(code, args.breakpoint)
440 self._debug_exec(code, args.breakpoint)
444
441
445 def _debug_post_mortem(self):
442 def _debug_post_mortem(self):
446 self.shell.debugger(force=True)
443 self.shell.debugger(force=True)
447
444
448 def _debug_exec(self, code, breakpoint):
445 def _debug_exec(self, code, breakpoint):
449 if breakpoint:
446 if breakpoint:
450 (filename, bp_line) = breakpoint.rsplit(':', 1)
447 (filename, bp_line) = breakpoint.rsplit(':', 1)
451 bp_line = int(bp_line)
448 bp_line = int(bp_line)
452 else:
449 else:
453 (filename, bp_line) = (None, None)
450 (filename, bp_line) = (None, None)
454 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
451 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
455
452
456 @line_magic
453 @line_magic
457 def tb(self, s):
454 def tb(self, s):
458 """Print the last traceback with the currently active exception mode.
455 """Print the last traceback with the currently active exception mode.
459
456
460 See %xmode for changing exception reporting modes."""
457 See %xmode for changing exception reporting modes."""
461 self.shell.showtraceback()
458 self.shell.showtraceback()
462
459
463 @skip_doctest
460 @skip_doctest
464 @line_magic
461 @line_magic
465 def run(self, parameter_s='', runner=None,
462 def run(self, parameter_s='', runner=None,
466 file_finder=get_py_filename):
463 file_finder=get_py_filename):
467 """Run the named file inside IPython as a program.
464 """Run the named file inside IPython as a program.
468
465
469 Usage::
466 Usage::
470
467
471 %run [-n -i -e -G]
468 %run [-n -i -e -G]
472 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
469 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
473 ( -m mod | file ) [args]
470 ( -m mod | file ) [args]
474
471
475 Parameters after the filename are passed as command-line arguments to
472 Parameters after the filename are passed as command-line arguments to
476 the program (put in sys.argv). Then, control returns to IPython's
473 the program (put in sys.argv). Then, control returns to IPython's
477 prompt.
474 prompt.
478
475
479 This is similar to running at a system prompt ``python file args``,
476 This is similar to running at a system prompt ``python file args``,
480 but with the advantage of giving you IPython's tracebacks, and of
477 but with the advantage of giving you IPython's tracebacks, and of
481 loading all variables into your interactive namespace for further use
478 loading all variables into your interactive namespace for further use
482 (unless -p is used, see below).
479 (unless -p is used, see below).
483
480
484 The file is executed in a namespace initially consisting only of
481 The file is executed in a namespace initially consisting only of
485 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
482 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
486 sees its environment as if it were being run as a stand-alone program
483 sees its environment as if it were being run as a stand-alone program
487 (except for sharing global objects such as previously imported
484 (except for sharing global objects such as previously imported
488 modules). But after execution, the IPython interactive namespace gets
485 modules). But after execution, the IPython interactive namespace gets
489 updated with all variables defined in the program (except for __name__
486 updated with all variables defined in the program (except for __name__
490 and sys.argv). This allows for very convenient loading of code for
487 and sys.argv). This allows for very convenient loading of code for
491 interactive work, while giving each program a 'clean sheet' to run in.
488 interactive work, while giving each program a 'clean sheet' to run in.
492
489
493 Arguments are expanded using shell-like glob match. Patterns
490 Arguments are expanded using shell-like glob match. Patterns
494 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
491 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
495 tilde '~' will be expanded into user's home directory. Unlike
492 tilde '~' will be expanded into user's home directory. Unlike
496 real shells, quotation does not suppress expansions. Use
493 real shells, quotation does not suppress expansions. Use
497 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
494 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
498 To completely disable these expansions, you can use -G flag.
495 To completely disable these expansions, you can use -G flag.
499
496
500 Options:
497 Options:
501
498
502 -n
499 -n
503 __name__ is NOT set to '__main__', but to the running file's name
500 __name__ is NOT set to '__main__', but to the running file's name
504 without extension (as python does under import). This allows running
501 without extension (as python does under import). This allows running
505 scripts and reloading the definitions in them without calling code
502 scripts and reloading the definitions in them without calling code
506 protected by an ``if __name__ == "__main__"`` clause.
503 protected by an ``if __name__ == "__main__"`` clause.
507
504
508 -i
505 -i
509 run the file in IPython's namespace instead of an empty one. This
506 run the file in IPython's namespace instead of an empty one. This
510 is useful if you are experimenting with code written in a text editor
507 is useful if you are experimenting with code written in a text editor
511 which depends on variables defined interactively.
508 which depends on variables defined interactively.
512
509
513 -e
510 -e
514 ignore sys.exit() calls or SystemExit exceptions in the script
511 ignore sys.exit() calls or SystemExit exceptions in the script
515 being run. This is particularly useful if IPython is being used to
512 being run. This is particularly useful if IPython is being used to
516 run unittests, which always exit with a sys.exit() call. In such
513 run unittests, which always exit with a sys.exit() call. In such
517 cases you are interested in the output of the test results, not in
514 cases you are interested in the output of the test results, not in
518 seeing a traceback of the unittest module.
515 seeing a traceback of the unittest module.
519
516
520 -t
517 -t
521 print timing information at the end of the run. IPython will give
518 print timing information at the end of the run. IPython will give
522 you an estimated CPU time consumption for your script, which under
519 you an estimated CPU time consumption for your script, which under
523 Unix uses the resource module to avoid the wraparound problems of
520 Unix uses the resource module to avoid the wraparound problems of
524 time.clock(). Under Unix, an estimate of time spent on system tasks
521 time.clock(). Under Unix, an estimate of time spent on system tasks
525 is also given (for Windows platforms this is reported as 0.0).
522 is also given (for Windows platforms this is reported as 0.0).
526
523
527 If -t is given, an additional ``-N<N>`` option can be given, where <N>
524 If -t is given, an additional ``-N<N>`` option can be given, where <N>
528 must be an integer indicating how many times you want the script to
525 must be an integer indicating how many times you want the script to
529 run. The final timing report will include total and per run results.
526 run. The final timing report will include total and per run results.
530
527
531 For example (testing the script uniq_stable.py)::
528 For example (testing the script uniq_stable.py)::
532
529
533 In [1]: run -t uniq_stable
530 In [1]: run -t uniq_stable
534
531
535 IPython CPU timings (estimated):
532 IPython CPU timings (estimated):
536 User : 0.19597 s.
533 User : 0.19597 s.
537 System: 0.0 s.
534 System: 0.0 s.
538
535
539 In [2]: run -t -N5 uniq_stable
536 In [2]: run -t -N5 uniq_stable
540
537
541 IPython CPU timings (estimated):
538 IPython CPU timings (estimated):
542 Total runs performed: 5
539 Total runs performed: 5
543 Times : Total Per run
540 Times : Total Per run
544 User : 0.910862 s, 0.1821724 s.
541 User : 0.910862 s, 0.1821724 s.
545 System: 0.0 s, 0.0 s.
542 System: 0.0 s, 0.0 s.
546
543
547 -d
544 -d
548 run your program under the control of pdb, the Python debugger.
545 run your program under the control of pdb, the Python debugger.
549 This allows you to execute your program step by step, watch variables,
546 This allows you to execute your program step by step, watch variables,
550 etc. Internally, what IPython does is similar to calling::
547 etc. Internally, what IPython does is similar to calling::
551
548
552 pdb.run('execfile("YOURFILENAME")')
549 pdb.run('execfile("YOURFILENAME")')
553
550
554 with a breakpoint set on line 1 of your file. You can change the line
551 with a breakpoint set on line 1 of your file. You can change the line
555 number for this automatic breakpoint to be <N> by using the -bN option
552 number for this automatic breakpoint to be <N> by using the -bN option
556 (where N must be an integer). For example::
553 (where N must be an integer). For example::
557
554
558 %run -d -b40 myscript
555 %run -d -b40 myscript
559
556
560 will set the first breakpoint at line 40 in myscript.py. Note that
557 will set the first breakpoint at line 40 in myscript.py. Note that
561 the first breakpoint must be set on a line which actually does
558 the first breakpoint must be set on a line which actually does
562 something (not a comment or docstring) for it to stop execution.
559 something (not a comment or docstring) for it to stop execution.
563
560
564 Or you can specify a breakpoint in a different file::
561 Or you can specify a breakpoint in a different file::
565
562
566 %run -d -b myotherfile.py:20 myscript
563 %run -d -b myotherfile.py:20 myscript
567
564
568 When the pdb debugger starts, you will see a (Pdb) prompt. You must
565 When the pdb debugger starts, you will see a (Pdb) prompt. You must
569 first enter 'c' (without quotes) to start execution up to the first
566 first enter 'c' (without quotes) to start execution up to the first
570 breakpoint.
567 breakpoint.
571
568
572 Entering 'help' gives information about the use of the debugger. You
569 Entering 'help' gives information about the use of the debugger. You
573 can easily see pdb's full documentation with "import pdb;pdb.help()"
570 can easily see pdb's full documentation with "import pdb;pdb.help()"
574 at a prompt.
571 at a prompt.
575
572
576 -p
573 -p
577 run program under the control of the Python profiler module (which
574 run program under the control of the Python profiler module (which
578 prints a detailed report of execution times, function calls, etc).
575 prints a detailed report of execution times, function calls, etc).
579
576
580 You can pass other options after -p which affect the behavior of the
577 You can pass other options after -p which affect the behavior of the
581 profiler itself. See the docs for %prun for details.
578 profiler itself. See the docs for %prun for details.
582
579
583 In this mode, the program's variables do NOT propagate back to the
580 In this mode, the program's variables do NOT propagate back to the
584 IPython interactive namespace (because they remain in the namespace
581 IPython interactive namespace (because they remain in the namespace
585 where the profiler executes them).
582 where the profiler executes them).
586
583
587 Internally this triggers a call to %prun, see its documentation for
584 Internally this triggers a call to %prun, see its documentation for
588 details on the options available specifically for profiling.
585 details on the options available specifically for profiling.
589
586
590 There is one special usage for which the text above doesn't apply:
587 There is one special usage for which the text above doesn't apply:
591 if the filename ends with .ipy[nb], the file is run as ipython script,
588 if the filename ends with .ipy[nb], the file is run as ipython script,
592 just as if the commands were written on IPython prompt.
589 just as if the commands were written on IPython prompt.
593
590
594 -m
591 -m
595 specify module name to load instead of script path. Similar to
592 specify module name to load instead of script path. Similar to
596 the -m option for the python interpreter. Use this option last if you
593 the -m option for the python interpreter. Use this option last if you
597 want to combine with other %run options. Unlike the python interpreter
594 want to combine with other %run options. Unlike the python interpreter
598 only source modules are allowed no .pyc or .pyo files.
595 only source modules are allowed no .pyc or .pyo files.
599 For example::
596 For example::
600
597
601 %run -m example
598 %run -m example
602
599
603 will run the example module.
600 will run the example module.
604
601
605 -G
602 -G
606 disable shell-like glob expansion of arguments.
603 disable shell-like glob expansion of arguments.
607
604
608 """
605 """
609
606
610 # get arguments and set sys.argv for program to be run.
607 # get arguments and set sys.argv for program to be run.
611 opts, arg_lst = self.parse_options(parameter_s,
608 opts, arg_lst = self.parse_options(parameter_s,
612 'nidtN:b:pD:l:rs:T:em:G',
609 'nidtN:b:pD:l:rs:T:em:G',
613 mode='list', list_all=1)
610 mode='list', list_all=1)
614 if "m" in opts:
611 if "m" in opts:
615 modulename = opts["m"][0]
612 modulename = opts["m"][0]
616 modpath = find_mod(modulename)
613 modpath = find_mod(modulename)
617 if modpath is None:
614 if modpath is None:
618 warn('%r is not a valid modulename on sys.path'%modulename)
615 warn('%r is not a valid modulename on sys.path'%modulename)
619 return
616 return
620 arg_lst = [modpath] + arg_lst
617 arg_lst = [modpath] + arg_lst
621 try:
618 try:
622 filename = file_finder(arg_lst[0])
619 filename = file_finder(arg_lst[0])
623 except IndexError:
620 except IndexError:
624 warn('you must provide at least a filename.')
621 warn('you must provide at least a filename.')
625 print('\n%run:\n', oinspect.getdoc(self.run))
622 print('\n%run:\n', oinspect.getdoc(self.run))
626 return
623 return
627 except IOError as e:
624 except IOError as e:
628 try:
625 try:
629 msg = str(e)
626 msg = str(e)
630 except UnicodeError:
627 except UnicodeError:
631 msg = e.message
628 msg = e.message
632 error(msg)
629 error(msg)
633 return
630 return
634
631
635 if filename.lower().endswith(('.ipy', '.ipynb')):
632 if filename.lower().endswith(('.ipy', '.ipynb')):
636 with preserve_keys(self.shell.user_ns, '__file__'):
633 with preserve_keys(self.shell.user_ns, '__file__'):
637 self.shell.user_ns['__file__'] = filename
634 self.shell.user_ns['__file__'] = filename
638 self.shell.safe_execfile_ipy(filename)
635 self.shell.safe_execfile_ipy(filename)
639 return
636 return
640
637
641 # Control the response to exit() calls made by the script being run
638 # Control the response to exit() calls made by the script being run
642 exit_ignore = 'e' in opts
639 exit_ignore = 'e' in opts
643
640
644 # Make sure that the running script gets a proper sys.argv as if it
641 # Make sure that the running script gets a proper sys.argv as if it
645 # were run from a system shell.
642 # were run from a system shell.
646 save_argv = sys.argv # save it for later restoring
643 save_argv = sys.argv # save it for later restoring
647
644
648 if 'G' in opts:
645 if 'G' in opts:
649 args = arg_lst[1:]
646 args = arg_lst[1:]
650 else:
647 else:
651 # tilde and glob expansion
648 # tilde and glob expansion
652 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
649 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
653
650
654 sys.argv = [filename] + args # put in the proper filename
651 sys.argv = [filename] + args # put in the proper filename
655 # protect sys.argv from potential unicode strings on Python 2:
656 if not py3compat.PY3:
657 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
658
652
659 if 'i' in opts:
653 if 'i' in opts:
660 # Run in user's interactive namespace
654 # Run in user's interactive namespace
661 prog_ns = self.shell.user_ns
655 prog_ns = self.shell.user_ns
662 __name__save = self.shell.user_ns['__name__']
656 __name__save = self.shell.user_ns['__name__']
663 prog_ns['__name__'] = '__main__'
657 prog_ns['__name__'] = '__main__'
664 main_mod = self.shell.user_module
658 main_mod = self.shell.user_module
665
659
666 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
660 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
667 # set the __file__ global in the script's namespace
661 # set the __file__ global in the script's namespace
668 # TK: Is this necessary in interactive mode?
662 # TK: Is this necessary in interactive mode?
669 prog_ns['__file__'] = filename
663 prog_ns['__file__'] = filename
670 else:
664 else:
671 # Run in a fresh, empty namespace
665 # Run in a fresh, empty namespace
672 if 'n' in opts:
666 if 'n' in opts:
673 name = os.path.splitext(os.path.basename(filename))[0]
667 name = os.path.splitext(os.path.basename(filename))[0]
674 else:
668 else:
675 name = '__main__'
669 name = '__main__'
676
670
677 # The shell MUST hold a reference to prog_ns so after %run
671 # The shell MUST hold a reference to prog_ns so after %run
678 # exits, the python deletion mechanism doesn't zero it out
672 # exits, the python deletion mechanism doesn't zero it out
679 # (leaving dangling references). See interactiveshell for details
673 # (leaving dangling references). See interactiveshell for details
680 main_mod = self.shell.new_main_mod(filename, name)
674 main_mod = self.shell.new_main_mod(filename, name)
681 prog_ns = main_mod.__dict__
675 prog_ns = main_mod.__dict__
682
676
683 # pickle fix. See interactiveshell for an explanation. But we need to
677 # pickle fix. See interactiveshell for an explanation. But we need to
684 # make sure that, if we overwrite __main__, we replace it at the end
678 # make sure that, if we overwrite __main__, we replace it at the end
685 main_mod_name = prog_ns['__name__']
679 main_mod_name = prog_ns['__name__']
686
680
687 if main_mod_name == '__main__':
681 if main_mod_name == '__main__':
688 restore_main = sys.modules['__main__']
682 restore_main = sys.modules['__main__']
689 else:
683 else:
690 restore_main = False
684 restore_main = False
691
685
692 # This needs to be undone at the end to prevent holding references to
686 # This needs to be undone at the end to prevent holding references to
693 # every single object ever created.
687 # every single object ever created.
694 sys.modules[main_mod_name] = main_mod
688 sys.modules[main_mod_name] = main_mod
695
689
696 if 'p' in opts or 'd' in opts:
690 if 'p' in opts or 'd' in opts:
697 if 'm' in opts:
691 if 'm' in opts:
698 code = 'run_module(modulename, prog_ns)'
692 code = 'run_module(modulename, prog_ns)'
699 code_ns = {
693 code_ns = {
700 'run_module': self.shell.safe_run_module,
694 'run_module': self.shell.safe_run_module,
701 'prog_ns': prog_ns,
695 'prog_ns': prog_ns,
702 'modulename': modulename,
696 'modulename': modulename,
703 }
697 }
704 else:
698 else:
705 if 'd' in opts:
699 if 'd' in opts:
706 # allow exceptions to raise in debug mode
700 # allow exceptions to raise in debug mode
707 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
701 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
708 else:
702 else:
709 code = 'execfile(filename, prog_ns)'
703 code = 'execfile(filename, prog_ns)'
710 code_ns = {
704 code_ns = {
711 'execfile': self.shell.safe_execfile,
705 'execfile': self.shell.safe_execfile,
712 'prog_ns': prog_ns,
706 'prog_ns': prog_ns,
713 'filename': get_py_filename(filename),
707 'filename': get_py_filename(filename),
714 }
708 }
715
709
716 try:
710 try:
717 stats = None
711 stats = None
718 if 'p' in opts:
712 if 'p' in opts:
719 stats = self._run_with_profiler(code, opts, code_ns)
713 stats = self._run_with_profiler(code, opts, code_ns)
720 else:
714 else:
721 if 'd' in opts:
715 if 'd' in opts:
722 bp_file, bp_line = parse_breakpoint(
716 bp_file, bp_line = parse_breakpoint(
723 opts.get('b', ['1'])[0], filename)
717 opts.get('b', ['1'])[0], filename)
724 self._run_with_debugger(
718 self._run_with_debugger(
725 code, code_ns, filename, bp_line, bp_file)
719 code, code_ns, filename, bp_line, bp_file)
726 else:
720 else:
727 if 'm' in opts:
721 if 'm' in opts:
728 def run():
722 def run():
729 self.shell.safe_run_module(modulename, prog_ns)
723 self.shell.safe_run_module(modulename, prog_ns)
730 else:
724 else:
731 if runner is None:
725 if runner is None:
732 runner = self.default_runner
726 runner = self.default_runner
733 if runner is None:
727 if runner is None:
734 runner = self.shell.safe_execfile
728 runner = self.shell.safe_execfile
735
729
736 def run():
730 def run():
737 runner(filename, prog_ns, prog_ns,
731 runner(filename, prog_ns, prog_ns,
738 exit_ignore=exit_ignore)
732 exit_ignore=exit_ignore)
739
733
740 if 't' in opts:
734 if 't' in opts:
741 # timed execution
735 # timed execution
742 try:
736 try:
743 nruns = int(opts['N'][0])
737 nruns = int(opts['N'][0])
744 if nruns < 1:
738 if nruns < 1:
745 error('Number of runs must be >=1')
739 error('Number of runs must be >=1')
746 return
740 return
747 except (KeyError):
741 except (KeyError):
748 nruns = 1
742 nruns = 1
749 self._run_with_timing(run, nruns)
743 self._run_with_timing(run, nruns)
750 else:
744 else:
751 # regular execution
745 # regular execution
752 run()
746 run()
753
747
754 if 'i' in opts:
748 if 'i' in opts:
755 self.shell.user_ns['__name__'] = __name__save
749 self.shell.user_ns['__name__'] = __name__save
756 else:
750 else:
757 # update IPython interactive namespace
751 # update IPython interactive namespace
758
752
759 # Some forms of read errors on the file may mean the
753 # Some forms of read errors on the file may mean the
760 # __name__ key was never set; using pop we don't have to
754 # __name__ key was never set; using pop we don't have to
761 # worry about a possible KeyError.
755 # worry about a possible KeyError.
762 prog_ns.pop('__name__', None)
756 prog_ns.pop('__name__', None)
763
757
764 with preserve_keys(self.shell.user_ns, '__file__'):
758 with preserve_keys(self.shell.user_ns, '__file__'):
765 self.shell.user_ns.update(prog_ns)
759 self.shell.user_ns.update(prog_ns)
766 finally:
760 finally:
767 # It's a bit of a mystery why, but __builtins__ can change from
761 # It's a bit of a mystery why, but __builtins__ can change from
768 # being a module to becoming a dict missing some key data after
762 # being a module to becoming a dict missing some key data after
769 # %run. As best I can see, this is NOT something IPython is doing
763 # %run. As best I can see, this is NOT something IPython is doing
770 # at all, and similar problems have been reported before:
764 # at all, and similar problems have been reported before:
771 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
765 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
772 # Since this seems to be done by the interpreter itself, the best
766 # Since this seems to be done by the interpreter itself, the best
773 # we can do is to at least restore __builtins__ for the user on
767 # we can do is to at least restore __builtins__ for the user on
774 # exit.
768 # exit.
775 self.shell.user_ns['__builtins__'] = builtin_mod
769 self.shell.user_ns['__builtins__'] = builtin_mod
776
770
777 # Ensure key global structures are restored
771 # Ensure key global structures are restored
778 sys.argv = save_argv
772 sys.argv = save_argv
779 if restore_main:
773 if restore_main:
780 sys.modules['__main__'] = restore_main
774 sys.modules['__main__'] = restore_main
781 else:
775 else:
782 # Remove from sys.modules the reference to main_mod we'd
776 # Remove from sys.modules the reference to main_mod we'd
783 # added. Otherwise it will trap references to objects
777 # added. Otherwise it will trap references to objects
784 # contained therein.
778 # contained therein.
785 del sys.modules[main_mod_name]
779 del sys.modules[main_mod_name]
786
780
787 return stats
781 return stats
788
782
789 def _run_with_debugger(self, code, code_ns, filename=None,
783 def _run_with_debugger(self, code, code_ns, filename=None,
790 bp_line=None, bp_file=None):
784 bp_line=None, bp_file=None):
791 """
785 """
792 Run `code` in debugger with a break point.
786 Run `code` in debugger with a break point.
793
787
794 Parameters
788 Parameters
795 ----------
789 ----------
796 code : str
790 code : str
797 Code to execute.
791 Code to execute.
798 code_ns : dict
792 code_ns : dict
799 A namespace in which `code` is executed.
793 A namespace in which `code` is executed.
800 filename : str
794 filename : str
801 `code` is ran as if it is in `filename`.
795 `code` is ran as if it is in `filename`.
802 bp_line : int, optional
796 bp_line : int, optional
803 Line number of the break point.
797 Line number of the break point.
804 bp_file : str, optional
798 bp_file : str, optional
805 Path to the file in which break point is specified.
799 Path to the file in which break point is specified.
806 `filename` is used if not given.
800 `filename` is used if not given.
807
801
808 Raises
802 Raises
809 ------
803 ------
810 UsageError
804 UsageError
811 If the break point given by `bp_line` is not valid.
805 If the break point given by `bp_line` is not valid.
812
806
813 """
807 """
814 deb = self.shell.InteractiveTB.pdb
808 deb = self.shell.InteractiveTB.pdb
815 if not deb:
809 if not deb:
816 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
810 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
817 deb = self.shell.InteractiveTB.pdb
811 deb = self.shell.InteractiveTB.pdb
818
812
819 # deb.checkline() fails if deb.curframe exists but is None; it can
813 # deb.checkline() fails if deb.curframe exists but is None; it can
820 # handle it not existing. https://github.com/ipython/ipython/issues/10028
814 # handle it not existing. https://github.com/ipython/ipython/issues/10028
821 if hasattr(deb, 'curframe'):
815 if hasattr(deb, 'curframe'):
822 del deb.curframe
816 del deb.curframe
823
817
824 # reset Breakpoint state, which is moronically kept
818 # reset Breakpoint state, which is moronically kept
825 # in a class
819 # in a class
826 bdb.Breakpoint.next = 1
820 bdb.Breakpoint.next = 1
827 bdb.Breakpoint.bplist = {}
821 bdb.Breakpoint.bplist = {}
828 bdb.Breakpoint.bpbynumber = [None]
822 bdb.Breakpoint.bpbynumber = [None]
829 if bp_line is not None:
823 if bp_line is not None:
830 # Set an initial breakpoint to stop execution
824 # Set an initial breakpoint to stop execution
831 maxtries = 10
825 maxtries = 10
832 bp_file = bp_file or filename
826 bp_file = bp_file or filename
833 checkline = deb.checkline(bp_file, bp_line)
827 checkline = deb.checkline(bp_file, bp_line)
834 if not checkline:
828 if not checkline:
835 for bp in range(bp_line + 1, bp_line + maxtries + 1):
829 for bp in range(bp_line + 1, bp_line + maxtries + 1):
836 if deb.checkline(bp_file, bp):
830 if deb.checkline(bp_file, bp):
837 break
831 break
838 else:
832 else:
839 msg = ("\nI failed to find a valid line to set "
833 msg = ("\nI failed to find a valid line to set "
840 "a breakpoint\n"
834 "a breakpoint\n"
841 "after trying up to line: %s.\n"
835 "after trying up to line: %s.\n"
842 "Please set a valid breakpoint manually "
836 "Please set a valid breakpoint manually "
843 "with the -b option." % bp)
837 "with the -b option." % bp)
844 raise UsageError(msg)
838 raise UsageError(msg)
845 # if we find a good linenumber, set the breakpoint
839 # if we find a good linenumber, set the breakpoint
846 deb.do_break('%s:%s' % (bp_file, bp_line))
840 deb.do_break('%s:%s' % (bp_file, bp_line))
847
841
848 if filename:
842 if filename:
849 # Mimic Pdb._runscript(...)
843 # Mimic Pdb._runscript(...)
850 deb._wait_for_mainpyfile = True
844 deb._wait_for_mainpyfile = True
851 deb.mainpyfile = deb.canonic(filename)
845 deb.mainpyfile = deb.canonic(filename)
852
846
853 # Start file run
847 # Start file run
854 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
848 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
855 try:
849 try:
856 if filename:
850 if filename:
857 # save filename so it can be used by methods on the deb object
851 # save filename so it can be used by methods on the deb object
858 deb._exec_filename = filename
852 deb._exec_filename = filename
859 while True:
853 while True:
860 try:
854 try:
861 deb.run(code, code_ns)
855 deb.run(code, code_ns)
862 except Restart:
856 except Restart:
863 print("Restarting")
857 print("Restarting")
864 if filename:
858 if filename:
865 deb._wait_for_mainpyfile = True
859 deb._wait_for_mainpyfile = True
866 deb.mainpyfile = deb.canonic(filename)
860 deb.mainpyfile = deb.canonic(filename)
867 continue
861 continue
868 else:
862 else:
869 break
863 break
870
864
871
865
872 except:
866 except:
873 etype, value, tb = sys.exc_info()
867 etype, value, tb = sys.exc_info()
874 # Skip three frames in the traceback: the %run one,
868 # Skip three frames in the traceback: the %run one,
875 # one inside bdb.py, and the command-line typed by the
869 # one inside bdb.py, and the command-line typed by the
876 # user (run by exec in pdb itself).
870 # user (run by exec in pdb itself).
877 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
871 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
878
872
879 @staticmethod
873 @staticmethod
880 def _run_with_timing(run, nruns):
874 def _run_with_timing(run, nruns):
881 """
875 """
882 Run function `run` and print timing information.
876 Run function `run` and print timing information.
883
877
884 Parameters
878 Parameters
885 ----------
879 ----------
886 run : callable
880 run : callable
887 Any callable object which takes no argument.
881 Any callable object which takes no argument.
888 nruns : int
882 nruns : int
889 Number of times to execute `run`.
883 Number of times to execute `run`.
890
884
891 """
885 """
892 twall0 = time.time()
886 twall0 = time.time()
893 if nruns == 1:
887 if nruns == 1:
894 t0 = clock2()
888 t0 = clock2()
895 run()
889 run()
896 t1 = clock2()
890 t1 = clock2()
897 t_usr = t1[0] - t0[0]
891 t_usr = t1[0] - t0[0]
898 t_sys = t1[1] - t0[1]
892 t_sys = t1[1] - t0[1]
899 print("\nIPython CPU timings (estimated):")
893 print("\nIPython CPU timings (estimated):")
900 print(" User : %10.2f s." % t_usr)
894 print(" User : %10.2f s." % t_usr)
901 print(" System : %10.2f s." % t_sys)
895 print(" System : %10.2f s." % t_sys)
902 else:
896 else:
903 runs = range(nruns)
897 runs = range(nruns)
904 t0 = clock2()
898 t0 = clock2()
905 for nr in runs:
899 for nr in runs:
906 run()
900 run()
907 t1 = clock2()
901 t1 = clock2()
908 t_usr = t1[0] - t0[0]
902 t_usr = t1[0] - t0[0]
909 t_sys = t1[1] - t0[1]
903 t_sys = t1[1] - t0[1]
910 print("\nIPython CPU timings (estimated):")
904 print("\nIPython CPU timings (estimated):")
911 print("Total runs performed:", nruns)
905 print("Total runs performed:", nruns)
912 print(" Times : %10s %10s" % ('Total', 'Per run'))
906 print(" Times : %10s %10s" % ('Total', 'Per run'))
913 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
907 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
914 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
908 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
915 twall1 = time.time()
909 twall1 = time.time()
916 print("Wall time: %10.2f s." % (twall1 - twall0))
910 print("Wall time: %10.2f s." % (twall1 - twall0))
917
911
918 @skip_doctest
912 @skip_doctest
919 @line_cell_magic
913 @line_cell_magic
920 def timeit(self, line='', cell=None):
914 def timeit(self, line='', cell=None):
921 """Time execution of a Python statement or expression
915 """Time execution of a Python statement or expression
922
916
923 Usage, in line mode:
917 Usage, in line mode:
924 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
918 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
925 or in cell mode:
919 or in cell mode:
926 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
920 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
927 code
921 code
928 code...
922 code...
929
923
930 Time execution of a Python statement or expression using the timeit
924 Time execution of a Python statement or expression using the timeit
931 module. This function can be used both as a line and cell magic:
925 module. This function can be used both as a line and cell magic:
932
926
933 - In line mode you can time a single-line statement (though multiple
927 - In line mode you can time a single-line statement (though multiple
934 ones can be chained with using semicolons).
928 ones can be chained with using semicolons).
935
929
936 - In cell mode, the statement in the first line is used as setup code
930 - In cell mode, the statement in the first line is used as setup code
937 (executed but not timed) and the body of the cell is timed. The cell
931 (executed but not timed) and the body of the cell is timed. The cell
938 body has access to any variables created in the setup code.
932 body has access to any variables created in the setup code.
939
933
940 Options:
934 Options:
941 -n<N>: execute the given statement <N> times in a loop. If this value
935 -n<N>: execute the given statement <N> times in a loop. If this value
942 is not given, a fitting value is chosen.
936 is not given, a fitting value is chosen.
943
937
944 -r<R>: repeat the loop iteration <R> times and take the best result.
938 -r<R>: repeat the loop iteration <R> times and take the best result.
945 Default: 3
939 Default: 3
946
940
947 -t: use time.time to measure the time, which is the default on Unix.
941 -t: use time.time to measure the time, which is the default on Unix.
948 This function measures wall time.
942 This function measures wall time.
949
943
950 -c: use time.clock to measure the time, which is the default on
944 -c: use time.clock to measure the time, which is the default on
951 Windows and measures wall time. On Unix, resource.getrusage is used
945 Windows and measures wall time. On Unix, resource.getrusage is used
952 instead and returns the CPU user time.
946 instead and returns the CPU user time.
953
947
954 -p<P>: use a precision of <P> digits to display the timing result.
948 -p<P>: use a precision of <P> digits to display the timing result.
955 Default: 3
949 Default: 3
956
950
957 -q: Quiet, do not print result.
951 -q: Quiet, do not print result.
958
952
959 -o: return a TimeitResult that can be stored in a variable to inspect
953 -o: return a TimeitResult that can be stored in a variable to inspect
960 the result in more details.
954 the result in more details.
961
955
962
956
963 Examples
957 Examples
964 --------
958 --------
965 ::
959 ::
966
960
967 In [1]: %timeit pass
961 In [1]: %timeit pass
968 100000000 loops, average of 7: 5.48 ns +- 0.354 ns per loop (using standard deviation)
962 100000000 loops, average of 7: 5.48 ns +- 0.354 ns per loop (using standard deviation)
969
963
970 In [2]: u = None
964 In [2]: u = None
971
965
972 In [3]: %timeit u is None
966 In [3]: %timeit u is None
973 10000000 loops, average of 7: 22.7 ns +- 2.33 ns per loop (using standard deviation)
967 10000000 loops, average of 7: 22.7 ns +- 2.33 ns per loop (using standard deviation)
974
968
975 In [4]: %timeit -r 4 u == None
969 In [4]: %timeit -r 4 u == None
976 10000000 loops, average of 4: 27.5 ns +- 2.91 ns per loop (using standard deviation)
970 10000000 loops, average of 4: 27.5 ns +- 2.91 ns per loop (using standard deviation)
977
971
978 In [5]: import time
972 In [5]: import time
979
973
980 In [6]: %timeit -n1 time.sleep(2)
974 In [6]: %timeit -n1 time.sleep(2)
981 1 loop, average of 7: 2 s +- 4.71 Β΅s per loop (using standard deviation)
975 1 loop, average of 7: 2 s +- 4.71 Β΅s per loop (using standard deviation)
982
976
983
977
984 The times reported by %timeit will be slightly higher than those
978 The times reported by %timeit will be slightly higher than those
985 reported by the timeit.py script when variables are accessed. This is
979 reported by the timeit.py script when variables are accessed. This is
986 due to the fact that %timeit executes the statement in the namespace
980 due to the fact that %timeit executes the statement in the namespace
987 of the shell, compared with timeit.py, which uses a single setup
981 of the shell, compared with timeit.py, which uses a single setup
988 statement to import function or create variables. Generally, the bias
982 statement to import function or create variables. Generally, the bias
989 does not matter as long as results from timeit.py are not mixed with
983 does not matter as long as results from timeit.py are not mixed with
990 those from %timeit."""
984 those from %timeit."""
991
985
992 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
986 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
993 posix=False, strict=False)
987 posix=False, strict=False)
994 if stmt == "" and cell is None:
988 if stmt == "" and cell is None:
995 return
989 return
996
990
997 timefunc = timeit.default_timer
991 timefunc = timeit.default_timer
998 number = int(getattr(opts, "n", 0))
992 number = int(getattr(opts, "n", 0))
999 default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat
993 default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat
1000 repeat = int(getattr(opts, "r", default_repeat))
994 repeat = int(getattr(opts, "r", default_repeat))
1001 precision = int(getattr(opts, "p", 3))
995 precision = int(getattr(opts, "p", 3))
1002 quiet = 'q' in opts
996 quiet = 'q' in opts
1003 return_result = 'o' in opts
997 return_result = 'o' in opts
1004 if hasattr(opts, "t"):
998 if hasattr(opts, "t"):
1005 timefunc = time.time
999 timefunc = time.time
1006 if hasattr(opts, "c"):
1000 if hasattr(opts, "c"):
1007 timefunc = clock
1001 timefunc = clock
1008
1002
1009 timer = Timer(timer=timefunc)
1003 timer = Timer(timer=timefunc)
1010 # this code has tight coupling to the inner workings of timeit.Timer,
1004 # this code has tight coupling to the inner workings of timeit.Timer,
1011 # but is there a better way to achieve that the code stmt has access
1005 # but is there a better way to achieve that the code stmt has access
1012 # to the shell namespace?
1006 # to the shell namespace?
1013 transform = self.shell.input_splitter.transform_cell
1007 transform = self.shell.input_splitter.transform_cell
1014
1008
1015 if cell is None:
1009 if cell is None:
1016 # called as line magic
1010 # called as line magic
1017 ast_setup = self.shell.compile.ast_parse("pass")
1011 ast_setup = self.shell.compile.ast_parse("pass")
1018 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1012 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1019 else:
1013 else:
1020 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1014 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1021 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1015 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1022
1016
1023 ast_setup = self.shell.transform_ast(ast_setup)
1017 ast_setup = self.shell.transform_ast(ast_setup)
1024 ast_stmt = self.shell.transform_ast(ast_stmt)
1018 ast_stmt = self.shell.transform_ast(ast_stmt)
1025
1019
1026 # This codestring is taken from timeit.template - we fill it in as an
1020 # This codestring is taken from timeit.template - we fill it in as an
1027 # AST, so that we can apply our AST transformations to the user code
1021 # AST, so that we can apply our AST transformations to the user code
1028 # without affecting the timing code.
1022 # without affecting the timing code.
1029 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1023 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1030 ' setup\n'
1024 ' setup\n'
1031 ' _t0 = _timer()\n'
1025 ' _t0 = _timer()\n'
1032 ' for _i in _it:\n'
1026 ' for _i in _it:\n'
1033 ' stmt\n'
1027 ' stmt\n'
1034 ' _t1 = _timer()\n'
1028 ' _t1 = _timer()\n'
1035 ' return _t1 - _t0\n')
1029 ' return _t1 - _t0\n')
1036
1030
1037 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1031 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1038 timeit_ast = ast.fix_missing_locations(timeit_ast)
1032 timeit_ast = ast.fix_missing_locations(timeit_ast)
1039
1033
1040 # Track compilation time so it can be reported if too long
1034 # Track compilation time so it can be reported if too long
1041 # Minimum time above which compilation time will be reported
1035 # Minimum time above which compilation time will be reported
1042 tc_min = 0.1
1036 tc_min = 0.1
1043
1037
1044 t0 = clock()
1038 t0 = clock()
1045 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1039 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1046 tc = clock()-t0
1040 tc = clock()-t0
1047
1041
1048 ns = {}
1042 ns = {}
1049 exec(code, self.shell.user_ns, ns)
1043 exec(code, self.shell.user_ns, ns)
1050 timer.inner = ns["inner"]
1044 timer.inner = ns["inner"]
1051
1045
1052 # This is used to check if there is a huge difference between the
1046 # This is used to check if there is a huge difference between the
1053 # best and worst timings.
1047 # best and worst timings.
1054 # Issue: https://github.com/ipython/ipython/issues/6471
1048 # Issue: https://github.com/ipython/ipython/issues/6471
1055 if number == 0:
1049 if number == 0:
1056 # determine number so that 0.2 <= total time < 2.0
1050 # determine number so that 0.2 <= total time < 2.0
1057 for index in range(0, 10):
1051 for index in range(0, 10):
1058 number = 10 ** index
1052 number = 10 ** index
1059 time_number = timer.timeit(number)
1053 time_number = timer.timeit(number)
1060 if time_number >= 0.2:
1054 if time_number >= 0.2:
1061 break
1055 break
1062
1056
1063 all_runs = timer.repeat(repeat, number)
1057 all_runs = timer.repeat(repeat, number)
1064 best = min(all_runs) / number
1058 best = min(all_runs) / number
1065 worst = max(all_runs) / number
1059 worst = max(all_runs) / number
1066 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1060 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1067
1061
1068 if not quiet :
1062 if not quiet :
1069 # Check best timing is greater than zero to avoid a
1063 # Check best timing is greater than zero to avoid a
1070 # ZeroDivisionError.
1064 # ZeroDivisionError.
1071 # In cases where the slowest timing is lesser than a micosecond
1065 # In cases where the slowest timing is lesser than a micosecond
1072 # we assume that it does not really matter if the fastest
1066 # we assume that it does not really matter if the fastest
1073 # timing is 4 times faster than the slowest timing or not.
1067 # timing is 4 times faster than the slowest timing or not.
1074 if worst > 4 * best and best > 0 and worst > 1e-6:
1068 if worst > 4 * best and best > 0 and worst > 1e-6:
1075 print("The slowest run took %0.2f times longer than the "
1069 print("The slowest run took %0.2f times longer than the "
1076 "fastest. This could mean that an intermediate result "
1070 "fastest. This could mean that an intermediate result "
1077 "is being cached." % (worst / best))
1071 "is being cached." % (worst / best))
1078
1072
1079 print( timeit_result )
1073 print( timeit_result )
1080
1074
1081 if tc > tc_min:
1075 if tc > tc_min:
1082 print("Compiler time: %.2f s" % tc)
1076 print("Compiler time: %.2f s" % tc)
1083 if return_result:
1077 if return_result:
1084 return timeit_result
1078 return timeit_result
1085
1079
1086 @skip_doctest
1080 @skip_doctest
1087 @needs_local_scope
1081 @needs_local_scope
1088 @line_cell_magic
1082 @line_cell_magic
1089 def time(self,line='', cell=None, local_ns=None):
1083 def time(self,line='', cell=None, local_ns=None):
1090 """Time execution of a Python statement or expression.
1084 """Time execution of a Python statement or expression.
1091
1085
1092 The CPU and wall clock times are printed, and the value of the
1086 The CPU and wall clock times are printed, and the value of the
1093 expression (if any) is returned. Note that under Win32, system time
1087 expression (if any) is returned. Note that under Win32, system time
1094 is always reported as 0, since it can not be measured.
1088 is always reported as 0, since it can not be measured.
1095
1089
1096 This function can be used both as a line and cell magic:
1090 This function can be used both as a line and cell magic:
1097
1091
1098 - In line mode you can time a single-line statement (though multiple
1092 - In line mode you can time a single-line statement (though multiple
1099 ones can be chained with using semicolons).
1093 ones can be chained with using semicolons).
1100
1094
1101 - In cell mode, you can time the cell body (a directly
1095 - In cell mode, you can time the cell body (a directly
1102 following statement raises an error).
1096 following statement raises an error).
1103
1097
1104 This function provides very basic timing functionality. Use the timeit
1098 This function provides very basic timing functionality. Use the timeit
1105 magic for more control over the measurement.
1099 magic for more control over the measurement.
1106
1100
1107 Examples
1101 Examples
1108 --------
1102 --------
1109 ::
1103 ::
1110
1104
1111 In [1]: %time 2**128
1105 In [1]: %time 2**128
1112 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1106 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1113 Wall time: 0.00
1107 Wall time: 0.00
1114 Out[1]: 340282366920938463463374607431768211456L
1108 Out[1]: 340282366920938463463374607431768211456L
1115
1109
1116 In [2]: n = 1000000
1110 In [2]: n = 1000000
1117
1111
1118 In [3]: %time sum(range(n))
1112 In [3]: %time sum(range(n))
1119 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1113 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1120 Wall time: 1.37
1114 Wall time: 1.37
1121 Out[3]: 499999500000L
1115 Out[3]: 499999500000L
1122
1116
1123 In [4]: %time print 'hello world'
1117 In [4]: %time print 'hello world'
1124 hello world
1118 hello world
1125 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1119 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1126 Wall time: 0.00
1120 Wall time: 0.00
1127
1121
1128 Note that the time needed by Python to compile the given expression
1122 Note that the time needed by Python to compile the given expression
1129 will be reported if it is more than 0.1s. In this example, the
1123 will be reported if it is more than 0.1s. In this example, the
1130 actual exponentiation is done by Python at compilation time, so while
1124 actual exponentiation is done by Python at compilation time, so while
1131 the expression can take a noticeable amount of time to compute, that
1125 the expression can take a noticeable amount of time to compute, that
1132 time is purely due to the compilation:
1126 time is purely due to the compilation:
1133
1127
1134 In [5]: %time 3**9999;
1128 In [5]: %time 3**9999;
1135 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1129 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1136 Wall time: 0.00 s
1130 Wall time: 0.00 s
1137
1131
1138 In [6]: %time 3**999999;
1132 In [6]: %time 3**999999;
1139 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1133 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1140 Wall time: 0.00 s
1134 Wall time: 0.00 s
1141 Compiler : 0.78 s
1135 Compiler : 0.78 s
1142 """
1136 """
1143
1137
1144 # fail immediately if the given expression can't be compiled
1138 # fail immediately if the given expression can't be compiled
1145
1139
1146 if line and cell:
1140 if line and cell:
1147 raise UsageError("Can't use statement directly after '%%time'!")
1141 raise UsageError("Can't use statement directly after '%%time'!")
1148
1142
1149 if cell:
1143 if cell:
1150 expr = self.shell.input_transformer_manager.transform_cell(cell)
1144 expr = self.shell.input_transformer_manager.transform_cell(cell)
1151 else:
1145 else:
1152 expr = self.shell.input_transformer_manager.transform_cell(line)
1146 expr = self.shell.input_transformer_manager.transform_cell(line)
1153
1147
1154 # Minimum time above which parse time will be reported
1148 # Minimum time above which parse time will be reported
1155 tp_min = 0.1
1149 tp_min = 0.1
1156
1150
1157 t0 = clock()
1151 t0 = clock()
1158 expr_ast = self.shell.compile.ast_parse(expr)
1152 expr_ast = self.shell.compile.ast_parse(expr)
1159 tp = clock()-t0
1153 tp = clock()-t0
1160
1154
1161 # Apply AST transformations
1155 # Apply AST transformations
1162 expr_ast = self.shell.transform_ast(expr_ast)
1156 expr_ast = self.shell.transform_ast(expr_ast)
1163
1157
1164 # Minimum time above which compilation time will be reported
1158 # Minimum time above which compilation time will be reported
1165 tc_min = 0.1
1159 tc_min = 0.1
1166
1160
1167 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1161 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1168 mode = 'eval'
1162 mode = 'eval'
1169 source = '<timed eval>'
1163 source = '<timed eval>'
1170 expr_ast = ast.Expression(expr_ast.body[0].value)
1164 expr_ast = ast.Expression(expr_ast.body[0].value)
1171 else:
1165 else:
1172 mode = 'exec'
1166 mode = 'exec'
1173 source = '<timed exec>'
1167 source = '<timed exec>'
1174 t0 = clock()
1168 t0 = clock()
1175 code = self.shell.compile(expr_ast, source, mode)
1169 code = self.shell.compile(expr_ast, source, mode)
1176 tc = clock()-t0
1170 tc = clock()-t0
1177
1171
1178 # skew measurement as little as possible
1172 # skew measurement as little as possible
1179 glob = self.shell.user_ns
1173 glob = self.shell.user_ns
1180 wtime = time.time
1174 wtime = time.time
1181 # time execution
1175 # time execution
1182 wall_st = wtime()
1176 wall_st = wtime()
1183 if mode=='eval':
1177 if mode=='eval':
1184 st = clock2()
1178 st = clock2()
1185 try:
1179 try:
1186 out = eval(code, glob, local_ns)
1180 out = eval(code, glob, local_ns)
1187 except:
1181 except:
1188 self.shell.showtraceback()
1182 self.shell.showtraceback()
1189 return
1183 return
1190 end = clock2()
1184 end = clock2()
1191 else:
1185 else:
1192 st = clock2()
1186 st = clock2()
1193 try:
1187 try:
1194 exec(code, glob, local_ns)
1188 exec(code, glob, local_ns)
1195 except:
1189 except:
1196 self.shell.showtraceback()
1190 self.shell.showtraceback()
1197 return
1191 return
1198 end = clock2()
1192 end = clock2()
1199 out = None
1193 out = None
1200 wall_end = wtime()
1194 wall_end = wtime()
1201 # Compute actual times and report
1195 # Compute actual times and report
1202 wall_time = wall_end-wall_st
1196 wall_time = wall_end-wall_st
1203 cpu_user = end[0]-st[0]
1197 cpu_user = end[0]-st[0]
1204 cpu_sys = end[1]-st[1]
1198 cpu_sys = end[1]-st[1]
1205 cpu_tot = cpu_user+cpu_sys
1199 cpu_tot = cpu_user+cpu_sys
1206 # On windows cpu_sys is always zero, so no new information to the next print
1200 # On windows cpu_sys is always zero, so no new information to the next print
1207 if sys.platform != 'win32':
1201 if sys.platform != 'win32':
1208 print("CPU times: user %s, sys: %s, total: %s" % \
1202 print("CPU times: user %s, sys: %s, total: %s" % \
1209 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1203 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1210 print("Wall time: %s" % _format_time(wall_time))
1204 print("Wall time: %s" % _format_time(wall_time))
1211 if tc > tc_min:
1205 if tc > tc_min:
1212 print("Compiler : %s" % _format_time(tc))
1206 print("Compiler : %s" % _format_time(tc))
1213 if tp > tp_min:
1207 if tp > tp_min:
1214 print("Parser : %s" % _format_time(tp))
1208 print("Parser : %s" % _format_time(tp))
1215 return out
1209 return out
1216
1210
1217 @skip_doctest
1211 @skip_doctest
1218 @line_magic
1212 @line_magic
1219 def macro(self, parameter_s=''):
1213 def macro(self, parameter_s=''):
1220 """Define a macro for future re-execution. It accepts ranges of history,
1214 """Define a macro for future re-execution. It accepts ranges of history,
1221 filenames or string objects.
1215 filenames or string objects.
1222
1216
1223 Usage:\\
1217 Usage:\\
1224 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1218 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1225
1219
1226 Options:
1220 Options:
1227
1221
1228 -r: use 'raw' input. By default, the 'processed' history is used,
1222 -r: use 'raw' input. By default, the 'processed' history is used,
1229 so that magics are loaded in their transformed version to valid
1223 so that magics are loaded in their transformed version to valid
1230 Python. If this option is given, the raw input as typed at the
1224 Python. If this option is given, the raw input as typed at the
1231 command line is used instead.
1225 command line is used instead.
1232
1226
1233 -q: quiet macro definition. By default, a tag line is printed
1227 -q: quiet macro definition. By default, a tag line is printed
1234 to indicate the macro has been created, and then the contents of
1228 to indicate the macro has been created, and then the contents of
1235 the macro are printed. If this option is given, then no printout
1229 the macro are printed. If this option is given, then no printout
1236 is produced once the macro is created.
1230 is produced once the macro is created.
1237
1231
1238 This will define a global variable called `name` which is a string
1232 This will define a global variable called `name` which is a string
1239 made of joining the slices and lines you specify (n1,n2,... numbers
1233 made of joining the slices and lines you specify (n1,n2,... numbers
1240 above) from your input history into a single string. This variable
1234 above) from your input history into a single string. This variable
1241 acts like an automatic function which re-executes those lines as if
1235 acts like an automatic function which re-executes those lines as if
1242 you had typed them. You just type 'name' at the prompt and the code
1236 you had typed them. You just type 'name' at the prompt and the code
1243 executes.
1237 executes.
1244
1238
1245 The syntax for indicating input ranges is described in %history.
1239 The syntax for indicating input ranges is described in %history.
1246
1240
1247 Note: as a 'hidden' feature, you can also use traditional python slice
1241 Note: as a 'hidden' feature, you can also use traditional python slice
1248 notation, where N:M means numbers N through M-1.
1242 notation, where N:M means numbers N through M-1.
1249
1243
1250 For example, if your history contains (print using %hist -n )::
1244 For example, if your history contains (print using %hist -n )::
1251
1245
1252 44: x=1
1246 44: x=1
1253 45: y=3
1247 45: y=3
1254 46: z=x+y
1248 46: z=x+y
1255 47: print x
1249 47: print x
1256 48: a=5
1250 48: a=5
1257 49: print 'x',x,'y',y
1251 49: print 'x',x,'y',y
1258
1252
1259 you can create a macro with lines 44 through 47 (included) and line 49
1253 you can create a macro with lines 44 through 47 (included) and line 49
1260 called my_macro with::
1254 called my_macro with::
1261
1255
1262 In [55]: %macro my_macro 44-47 49
1256 In [55]: %macro my_macro 44-47 49
1263
1257
1264 Now, typing `my_macro` (without quotes) will re-execute all this code
1258 Now, typing `my_macro` (without quotes) will re-execute all this code
1265 in one pass.
1259 in one pass.
1266
1260
1267 You don't need to give the line-numbers in order, and any given line
1261 You don't need to give the line-numbers in order, and any given line
1268 number can appear multiple times. You can assemble macros with any
1262 number can appear multiple times. You can assemble macros with any
1269 lines from your input history in any order.
1263 lines from your input history in any order.
1270
1264
1271 The macro is a simple object which holds its value in an attribute,
1265 The macro is a simple object which holds its value in an attribute,
1272 but IPython's display system checks for macros and executes them as
1266 but IPython's display system checks for macros and executes them as
1273 code instead of printing them when you type their name.
1267 code instead of printing them when you type their name.
1274
1268
1275 You can view a macro's contents by explicitly printing it with::
1269 You can view a macro's contents by explicitly printing it with::
1276
1270
1277 print macro_name
1271 print macro_name
1278
1272
1279 """
1273 """
1280 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1274 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1281 if not args: # List existing macros
1275 if not args: # List existing macros
1282 return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro))
1276 return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro))
1283 if len(args) == 1:
1277 if len(args) == 1:
1284 raise UsageError(
1278 raise UsageError(
1285 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1279 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1286 name, codefrom = args[0], " ".join(args[1:])
1280 name, codefrom = args[0], " ".join(args[1:])
1287
1281
1288 #print 'rng',ranges # dbg
1282 #print 'rng',ranges # dbg
1289 try:
1283 try:
1290 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1284 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1291 except (ValueError, TypeError) as e:
1285 except (ValueError, TypeError) as e:
1292 print(e.args[0])
1286 print(e.args[0])
1293 return
1287 return
1294 macro = Macro(lines)
1288 macro = Macro(lines)
1295 self.shell.define_macro(name, macro)
1289 self.shell.define_macro(name, macro)
1296 if not ( 'q' in opts) :
1290 if not ( 'q' in opts) :
1297 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1291 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1298 print('=== Macro contents: ===')
1292 print('=== Macro contents: ===')
1299 print(macro, end=' ')
1293 print(macro, end=' ')
1300
1294
1301 @magic_arguments.magic_arguments()
1295 @magic_arguments.magic_arguments()
1302 @magic_arguments.argument('output', type=str, default='', nargs='?',
1296 @magic_arguments.argument('output', type=str, default='', nargs='?',
1303 help="""The name of the variable in which to store output.
1297 help="""The name of the variable in which to store output.
1304 This is a utils.io.CapturedIO object with stdout/err attributes
1298 This is a utils.io.CapturedIO object with stdout/err attributes
1305 for the text of the captured output.
1299 for the text of the captured output.
1306
1300
1307 CapturedOutput also has a show() method for displaying the output,
1301 CapturedOutput also has a show() method for displaying the output,
1308 and __call__ as well, so you can use that to quickly display the
1302 and __call__ as well, so you can use that to quickly display the
1309 output.
1303 output.
1310
1304
1311 If unspecified, captured output is discarded.
1305 If unspecified, captured output is discarded.
1312 """
1306 """
1313 )
1307 )
1314 @magic_arguments.argument('--no-stderr', action="store_true",
1308 @magic_arguments.argument('--no-stderr', action="store_true",
1315 help="""Don't capture stderr."""
1309 help="""Don't capture stderr."""
1316 )
1310 )
1317 @magic_arguments.argument('--no-stdout', action="store_true",
1311 @magic_arguments.argument('--no-stdout', action="store_true",
1318 help="""Don't capture stdout."""
1312 help="""Don't capture stdout."""
1319 )
1313 )
1320 @magic_arguments.argument('--no-display', action="store_true",
1314 @magic_arguments.argument('--no-display', action="store_true",
1321 help="""Don't capture IPython's rich display."""
1315 help="""Don't capture IPython's rich display."""
1322 )
1316 )
1323 @cell_magic
1317 @cell_magic
1324 def capture(self, line, cell):
1318 def capture(self, line, cell):
1325 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1319 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1326 args = magic_arguments.parse_argstring(self.capture, line)
1320 args = magic_arguments.parse_argstring(self.capture, line)
1327 out = not args.no_stdout
1321 out = not args.no_stdout
1328 err = not args.no_stderr
1322 err = not args.no_stderr
1329 disp = not args.no_display
1323 disp = not args.no_display
1330 with capture_output(out, err, disp) as io:
1324 with capture_output(out, err, disp) as io:
1331 self.shell.run_cell(cell)
1325 self.shell.run_cell(cell)
1332 if args.output:
1326 if args.output:
1333 self.shell.user_ns[args.output] = io
1327 self.shell.user_ns[args.output] = io
1334
1328
1335 def parse_breakpoint(text, current_file):
1329 def parse_breakpoint(text, current_file):
1336 '''Returns (file, line) for file:line and (current_file, line) for line'''
1330 '''Returns (file, line) for file:line and (current_file, line) for line'''
1337 colon = text.find(':')
1331 colon = text.find(':')
1338 if colon == -1:
1332 if colon == -1:
1339 return current_file, int(text)
1333 return current_file, int(text)
1340 else:
1334 else:
1341 return text[:colon], int(text[colon+1:])
1335 return text[:colon], int(text[colon+1:])
1342
1336
1343 def _format_time(timespan, precision=3):
1337 def _format_time(timespan, precision=3):
1344 """Formats the timespan in a human readable form"""
1338 """Formats the timespan in a human readable form"""
1345
1339
1346 if timespan >= 60.0:
1340 if timespan >= 60.0:
1347 # we have more than a minute, format that in a human readable form
1341 # we have more than a minute, format that in a human readable form
1348 # Idea from http://snipplr.com/view/5713/
1342 # Idea from http://snipplr.com/view/5713/
1349 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1343 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1350 time = []
1344 time = []
1351 leftover = timespan
1345 leftover = timespan
1352 for suffix, length in parts:
1346 for suffix, length in parts:
1353 value = int(leftover / length)
1347 value = int(leftover / length)
1354 if value > 0:
1348 if value > 0:
1355 leftover = leftover % length
1349 leftover = leftover % length
1356 time.append(u'%s%s' % (str(value), suffix))
1350 time.append(u'%s%s' % (str(value), suffix))
1357 if leftover < 1:
1351 if leftover < 1:
1358 break
1352 break
1359 return " ".join(time)
1353 return " ".join(time)
1360
1354
1361
1355
1362 # Unfortunately the unicode 'micro' symbol can cause problems in
1356 # Unfortunately the unicode 'micro' symbol can cause problems in
1363 # certain terminals.
1357 # certain terminals.
1364 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1358 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1365 # Try to prevent crashes by being more secure than it needs to
1359 # Try to prevent crashes by being more secure than it needs to
1366 # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set.
1360 # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set.
1367 units = [u"s", u"ms",u'us',"ns"] # the save value
1361 units = [u"s", u"ms",u'us',"ns"] # the save value
1368 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1362 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1369 try:
1363 try:
1370 u'\xb5'.encode(sys.stdout.encoding)
1364 u'\xb5'.encode(sys.stdout.encoding)
1371 units = [u"s", u"ms",u'\xb5s',"ns"]
1365 units = [u"s", u"ms",u'\xb5s',"ns"]
1372 except:
1366 except:
1373 pass
1367 pass
1374 scaling = [1, 1e3, 1e6, 1e9]
1368 scaling = [1, 1e3, 1e6, 1e9]
1375
1369
1376 if timespan > 0.0:
1370 if timespan > 0.0:
1377 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1371 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1378 else:
1372 else:
1379 order = 3
1373 order = 3
1380 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
1374 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
@@ -1,42 +1,39 b''
1 # coding: utf-8
1 # coding: utf-8
2 import nose.tools as nt
2 import nose.tools as nt
3
3
4 from IPython.core.splitinput import split_user_input, LineInfo
4 from IPython.core.splitinput import split_user_input, LineInfo
5 from IPython.testing import tools as tt
5 from IPython.testing import tools as tt
6 from IPython.utils import py3compat
6 from IPython.utils import py3compat
7
7
8 tests = [
8 tests = [
9 ('x=1', ('', '', 'x', '=1')),
9 ('x=1', ('', '', 'x', '=1')),
10 ('?', ('', '?', '', '')),
10 ('?', ('', '?', '', '')),
11 ('??', ('', '??', '', '')),
11 ('??', ('', '??', '', '')),
12 (' ?', (' ', '?', '', '')),
12 (' ?', (' ', '?', '', '')),
13 (' ??', (' ', '??', '', '')),
13 (' ??', (' ', '??', '', '')),
14 ('??x', ('', '??', 'x', '')),
14 ('??x', ('', '??', 'x', '')),
15 ('?x=1', ('', '?', 'x', '=1')),
15 ('?x=1', ('', '?', 'x', '=1')),
16 ('!ls', ('', '!', 'ls', '')),
16 ('!ls', ('', '!', 'ls', '')),
17 (' !ls', (' ', '!', 'ls', '')),
17 (' !ls', (' ', '!', 'ls', '')),
18 ('!!ls', ('', '!!', 'ls', '')),
18 ('!!ls', ('', '!!', 'ls', '')),
19 (' !!ls', (' ', '!!', 'ls', '')),
19 (' !!ls', (' ', '!!', 'ls', '')),
20 (',ls', ('', ',', 'ls', '')),
20 (',ls', ('', ',', 'ls', '')),
21 (';ls', ('', ';', 'ls', '')),
21 (';ls', ('', ';', 'ls', '')),
22 (' ;ls', (' ', ';', 'ls', '')),
22 (' ;ls', (' ', ';', 'ls', '')),
23 ('f.g(x)', ('', '', 'f.g', '(x)')),
23 ('f.g(x)', ('', '', 'f.g', '(x)')),
24 ('f.g (x)', ('', '', 'f.g', '(x)')),
24 ('f.g (x)', ('', '', 'f.g', '(x)')),
25 ('?%hist1', ('', '?', '%hist1', '')),
25 ('?%hist1', ('', '?', '%hist1', '')),
26 ('?%%hist2', ('', '?', '%%hist2', '')),
26 ('?%%hist2', ('', '?', '%%hist2', '')),
27 ('??%hist3', ('', '??', '%hist3', '')),
27 ('??%hist3', ('', '??', '%hist3', '')),
28 ('??%%hist4', ('', '??', '%%hist4', '')),
28 ('??%%hist4', ('', '??', '%%hist4', '')),
29 ('?x*', ('', '?', 'x*', '')),
29 ('?x*', ('', '?', 'x*', '')),
30 ]
30 ]
31 if py3compat.PY3:
31 tests.append((u"PΓ©rez Fernando", (u'', u'', u'PΓ©rez', u'Fernando')))
32 tests.append((u"PΓ©rez Fernando", (u'', u'', u'PΓ©rez', u'Fernando')))
33 else:
34 tests.append((u"PΓ©rez Fernando", (u'', u'', u'P', u'Γ©rez Fernando')))
35
32
36 def test_split_user_input():
33 def test_split_user_input():
37 return tt.check_pairs(split_user_input, tests)
34 return tt.check_pairs(split_user_input, tests)
38
35
39 def test_LineInfo():
36 def test_LineInfo():
40 """Simple test for LineInfo construction and str()"""
37 """Simple test for LineInfo construction and str()"""
41 linfo = LineInfo(' %cd /home')
38 linfo = LineInfo(' %cd /home')
42 nt.assert_equal(str(linfo), 'LineInfo [ |%|cd|/home]')
39 nt.assert_equal(str(linfo), 'LineInfo [ |%|cd|/home]')
@@ -1,1469 +1,1462 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Verbose and colourful traceback formatting.
3 Verbose and colourful traceback formatting.
4
4
5 **ColorTB**
5 **ColorTB**
6
6
7 I've always found it a bit hard to visually parse tracebacks in Python. The
7 I've always found it a bit hard to visually parse tracebacks in Python. The
8 ColorTB class is a solution to that problem. It colors the different parts of a
8 ColorTB class is a solution to that problem. It colors the different parts of a
9 traceback in a manner similar to what you would expect from a syntax-highlighting
9 traceback in a manner similar to what you would expect from a syntax-highlighting
10 text editor.
10 text editor.
11
11
12 Installation instructions for ColorTB::
12 Installation instructions for ColorTB::
13
13
14 import sys,ultratb
14 import sys,ultratb
15 sys.excepthook = ultratb.ColorTB()
15 sys.excepthook = ultratb.ColorTB()
16
16
17 **VerboseTB**
17 **VerboseTB**
18
18
19 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
19 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
20 of useful info when a traceback occurs. Ping originally had it spit out HTML
20 of useful info when a traceback occurs. Ping originally had it spit out HTML
21 and intended it for CGI programmers, but why should they have all the fun? I
21 and intended it for CGI programmers, but why should they have all the fun? I
22 altered it to spit out colored text to the terminal. It's a bit overwhelming,
22 altered it to spit out colored text to the terminal. It's a bit overwhelming,
23 but kind of neat, and maybe useful for long-running programs that you believe
23 but kind of neat, and maybe useful for long-running programs that you believe
24 are bug-free. If a crash *does* occur in that type of program you want details.
24 are bug-free. If a crash *does* occur in that type of program you want details.
25 Give it a shot--you'll love it or you'll hate it.
25 Give it a shot--you'll love it or you'll hate it.
26
26
27 .. note::
27 .. note::
28
28
29 The Verbose mode prints the variables currently visible where the exception
29 The Verbose mode prints the variables currently visible where the exception
30 happened (shortening their strings if too long). This can potentially be
30 happened (shortening their strings if too long). This can potentially be
31 very slow, if you happen to have a huge data structure whose string
31 very slow, if you happen to have a huge data structure whose string
32 representation is complex to compute. Your computer may appear to freeze for
32 representation is complex to compute. Your computer may appear to freeze for
33 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
33 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
34 with Ctrl-C (maybe hitting it more than once).
34 with Ctrl-C (maybe hitting it more than once).
35
35
36 If you encounter this kind of situation often, you may want to use the
36 If you encounter this kind of situation often, you may want to use the
37 Verbose_novars mode instead of the regular Verbose, which avoids formatting
37 Verbose_novars mode instead of the regular Verbose, which avoids formatting
38 variables (but otherwise includes the information and context given by
38 variables (but otherwise includes the information and context given by
39 Verbose).
39 Verbose).
40
40
41 .. note::
41 .. note::
42
42
43 The verbose mode print all variables in the stack, which means it can
43 The verbose mode print all variables in the stack, which means it can
44 potentially leak sensitive information like access keys, or unencryted
44 potentially leak sensitive information like access keys, or unencryted
45 password.
45 password.
46
46
47 Installation instructions for VerboseTB::
47 Installation instructions for VerboseTB::
48
48
49 import sys,ultratb
49 import sys,ultratb
50 sys.excepthook = ultratb.VerboseTB()
50 sys.excepthook = ultratb.VerboseTB()
51
51
52 Note: Much of the code in this module was lifted verbatim from the standard
52 Note: Much of the code in this module was lifted verbatim from the standard
53 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
53 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
54
54
55 Color schemes
55 Color schemes
56 -------------
56 -------------
57
57
58 The colors are defined in the class TBTools through the use of the
58 The colors are defined in the class TBTools through the use of the
59 ColorSchemeTable class. Currently the following exist:
59 ColorSchemeTable class. Currently the following exist:
60
60
61 - NoColor: allows all of this module to be used in any terminal (the color
61 - NoColor: allows all of this module to be used in any terminal (the color
62 escapes are just dummy blank strings).
62 escapes are just dummy blank strings).
63
63
64 - Linux: is meant to look good in a terminal like the Linux console (black
64 - Linux: is meant to look good in a terminal like the Linux console (black
65 or very dark background).
65 or very dark background).
66
66
67 - LightBG: similar to Linux but swaps dark/light colors to be more readable
67 - LightBG: similar to Linux but swaps dark/light colors to be more readable
68 in light background terminals.
68 in light background terminals.
69
69
70 - Neutral: a neutral color scheme that should be readable on both light and
70 - Neutral: a neutral color scheme that should be readable on both light and
71 dark background
71 dark background
72
72
73 You can implement other color schemes easily, the syntax is fairly
73 You can implement other color schemes easily, the syntax is fairly
74 self-explanatory. Please send back new schemes you develop to the author for
74 self-explanatory. Please send back new schemes you develop to the author for
75 possible inclusion in future releases.
75 possible inclusion in future releases.
76
76
77 Inheritance diagram:
77 Inheritance diagram:
78
78
79 .. inheritance-diagram:: IPython.core.ultratb
79 .. inheritance-diagram:: IPython.core.ultratb
80 :parts: 3
80 :parts: 3
81 """
81 """
82
82
83 #*****************************************************************************
83 #*****************************************************************************
84 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
84 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
85 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
85 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
86 #
86 #
87 # Distributed under the terms of the BSD License. The full license is in
87 # Distributed under the terms of the BSD License. The full license is in
88 # the file COPYING, distributed as part of this software.
88 # the file COPYING, distributed as part of this software.
89 #*****************************************************************************
89 #*****************************************************************************
90
90
91
91
92 import dis
92 import dis
93 import inspect
93 import inspect
94 import keyword
94 import keyword
95 import linecache
95 import linecache
96 import os
96 import os
97 import pydoc
97 import pydoc
98 import re
98 import re
99 import sys
99 import sys
100 import time
100 import time
101 import tokenize
101 import tokenize
102 import traceback
102 import traceback
103 import types
103 import types
104
104
105 try: # Python 2
105 try: # Python 2
106 generate_tokens = tokenize.generate_tokens
106 generate_tokens = tokenize.generate_tokens
107 except AttributeError: # Python 3
107 except AttributeError: # Python 3
108 generate_tokens = tokenize.tokenize
108 generate_tokens = tokenize.tokenize
109
109
110 # For purposes of monkeypatching inspect to fix a bug in it.
110 # For purposes of monkeypatching inspect to fix a bug in it.
111 from inspect import getsourcefile, getfile, getmodule, \
111 from inspect import getsourcefile, getfile, getmodule, \
112 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
112 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
113
113
114 # IPython's own modules
114 # IPython's own modules
115 from IPython import get_ipython
115 from IPython import get_ipython
116 from IPython.core import debugger
116 from IPython.core import debugger
117 from IPython.core.display_trap import DisplayTrap
117 from IPython.core.display_trap import DisplayTrap
118 from IPython.core.excolors import exception_colors
118 from IPython.core.excolors import exception_colors
119 from IPython.utils import PyColorize
119 from IPython.utils import PyColorize
120 from IPython.utils import openpy
120 from IPython.utils import openpy
121 from IPython.utils import path as util_path
121 from IPython.utils import path as util_path
122 from IPython.utils import py3compat
122 from IPython.utils import py3compat
123 from IPython.utils import ulinecache
123 from IPython.utils import ulinecache
124 from IPython.utils.data import uniq_stable
124 from IPython.utils.data import uniq_stable
125 from IPython.utils.terminal import get_terminal_size
125 from IPython.utils.terminal import get_terminal_size
126 from logging import info, error
126 from logging import info, error
127
127
128 import IPython.utils.colorable as colorable
128 import IPython.utils.colorable as colorable
129
129
130 # Globals
130 # Globals
131 # amount of space to put line numbers before verbose tracebacks
131 # amount of space to put line numbers before verbose tracebacks
132 INDENT_SIZE = 8
132 INDENT_SIZE = 8
133
133
134 # Default color scheme. This is used, for example, by the traceback
134 # Default color scheme. This is used, for example, by the traceback
135 # formatter. When running in an actual IPython instance, the user's rc.colors
135 # formatter. When running in an actual IPython instance, the user's rc.colors
136 # value is used, but having a module global makes this functionality available
136 # value is used, but having a module global makes this functionality available
137 # to users of ultratb who are NOT running inside ipython.
137 # to users of ultratb who are NOT running inside ipython.
138 DEFAULT_SCHEME = 'NoColor'
138 DEFAULT_SCHEME = 'NoColor'
139
139
140 # ---------------------------------------------------------------------------
140 # ---------------------------------------------------------------------------
141 # Code begins
141 # Code begins
142
142
143 # Utility functions
143 # Utility functions
144 def inspect_error():
144 def inspect_error():
145 """Print a message about internal inspect errors.
145 """Print a message about internal inspect errors.
146
146
147 These are unfortunately quite common."""
147 These are unfortunately quite common."""
148
148
149 error('Internal Python error in the inspect module.\n'
149 error('Internal Python error in the inspect module.\n'
150 'Below is the traceback from this internal error.\n')
150 'Below is the traceback from this internal error.\n')
151
151
152
152
153 # This function is a monkeypatch we apply to the Python inspect module. We have
153 # This function is a monkeypatch we apply to the Python inspect module. We have
154 # now found when it's needed (see discussion on issue gh-1456), and we have a
154 # now found when it's needed (see discussion on issue gh-1456), and we have a
155 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
155 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
156 # the monkeypatch is not applied. TK, Aug 2012.
156 # the monkeypatch is not applied. TK, Aug 2012.
157 def findsource(object):
157 def findsource(object):
158 """Return the entire source file and starting line number for an object.
158 """Return the entire source file and starting line number for an object.
159
159
160 The argument may be a module, class, method, function, traceback, frame,
160 The argument may be a module, class, method, function, traceback, frame,
161 or code object. The source code is returned as a list of all the lines
161 or code object. The source code is returned as a list of all the lines
162 in the file and the line number indexes a line in that list. An IOError
162 in the file and the line number indexes a line in that list. An IOError
163 is raised if the source code cannot be retrieved.
163 is raised if the source code cannot be retrieved.
164
164
165 FIXED version with which we monkeypatch the stdlib to work around a bug."""
165 FIXED version with which we monkeypatch the stdlib to work around a bug."""
166
166
167 file = getsourcefile(object) or getfile(object)
167 file = getsourcefile(object) or getfile(object)
168 # If the object is a frame, then trying to get the globals dict from its
168 # If the object is a frame, then trying to get the globals dict from its
169 # module won't work. Instead, the frame object itself has the globals
169 # module won't work. Instead, the frame object itself has the globals
170 # dictionary.
170 # dictionary.
171 globals_dict = None
171 globals_dict = None
172 if inspect.isframe(object):
172 if inspect.isframe(object):
173 # XXX: can this ever be false?
173 # XXX: can this ever be false?
174 globals_dict = object.f_globals
174 globals_dict = object.f_globals
175 else:
175 else:
176 module = getmodule(object, file)
176 module = getmodule(object, file)
177 if module:
177 if module:
178 globals_dict = module.__dict__
178 globals_dict = module.__dict__
179 lines = linecache.getlines(file, globals_dict)
179 lines = linecache.getlines(file, globals_dict)
180 if not lines:
180 if not lines:
181 raise IOError('could not get source code')
181 raise IOError('could not get source code')
182
182
183 if ismodule(object):
183 if ismodule(object):
184 return lines, 0
184 return lines, 0
185
185
186 if isclass(object):
186 if isclass(object):
187 name = object.__name__
187 name = object.__name__
188 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
188 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
189 # make some effort to find the best matching class definition:
189 # make some effort to find the best matching class definition:
190 # use the one with the least indentation, which is the one
190 # use the one with the least indentation, which is the one
191 # that's most probably not inside a function definition.
191 # that's most probably not inside a function definition.
192 candidates = []
192 candidates = []
193 for i in range(len(lines)):
193 for i in range(len(lines)):
194 match = pat.match(lines[i])
194 match = pat.match(lines[i])
195 if match:
195 if match:
196 # if it's at toplevel, it's already the best one
196 # if it's at toplevel, it's already the best one
197 if lines[i][0] == 'c':
197 if lines[i][0] == 'c':
198 return lines, i
198 return lines, i
199 # else add whitespace to candidate list
199 # else add whitespace to candidate list
200 candidates.append((match.group(1), i))
200 candidates.append((match.group(1), i))
201 if candidates:
201 if candidates:
202 # this will sort by whitespace, and by line number,
202 # this will sort by whitespace, and by line number,
203 # less whitespace first
203 # less whitespace first
204 candidates.sort()
204 candidates.sort()
205 return lines, candidates[0][1]
205 return lines, candidates[0][1]
206 else:
206 else:
207 raise IOError('could not find class definition')
207 raise IOError('could not find class definition')
208
208
209 if ismethod(object):
209 if ismethod(object):
210 object = object.__func__
210 object = object.__func__
211 if isfunction(object):
211 if isfunction(object):
212 object = object.__code__
212 object = object.__code__
213 if istraceback(object):
213 if istraceback(object):
214 object = object.tb_frame
214 object = object.tb_frame
215 if isframe(object):
215 if isframe(object):
216 object = object.f_code
216 object = object.f_code
217 if iscode(object):
217 if iscode(object):
218 if not hasattr(object, 'co_firstlineno'):
218 if not hasattr(object, 'co_firstlineno'):
219 raise IOError('could not find function definition')
219 raise IOError('could not find function definition')
220 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
220 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
221 pmatch = pat.match
221 pmatch = pat.match
222 # fperez - fix: sometimes, co_firstlineno can give a number larger than
222 # fperez - fix: sometimes, co_firstlineno can give a number larger than
223 # the length of lines, which causes an error. Safeguard against that.
223 # the length of lines, which causes an error. Safeguard against that.
224 lnum = min(object.co_firstlineno, len(lines)) - 1
224 lnum = min(object.co_firstlineno, len(lines)) - 1
225 while lnum > 0:
225 while lnum > 0:
226 if pmatch(lines[lnum]):
226 if pmatch(lines[lnum]):
227 break
227 break
228 lnum -= 1
228 lnum -= 1
229
229
230 return lines, lnum
230 return lines, lnum
231 raise IOError('could not find code object')
231 raise IOError('could not find code object')
232
232
233
233
234 # This is a patched version of inspect.getargs that applies the (unmerged)
234 # This is a patched version of inspect.getargs that applies the (unmerged)
235 # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes
235 # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes
236 # https://github.com/ipython/ipython/issues/8205 and
236 # https://github.com/ipython/ipython/issues/8205 and
237 # https://github.com/ipython/ipython/issues/8293
237 # https://github.com/ipython/ipython/issues/8293
238 def getargs(co):
238 def getargs(co):
239 """Get information about the arguments accepted by a code object.
239 """Get information about the arguments accepted by a code object.
240
240
241 Three things are returned: (args, varargs, varkw), where 'args' is
241 Three things are returned: (args, varargs, varkw), where 'args' is
242 a list of argument names (possibly containing nested lists), and
242 a list of argument names (possibly containing nested lists), and
243 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
243 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
244 if not iscode(co):
244 if not iscode(co):
245 raise TypeError('{!r} is not a code object'.format(co))
245 raise TypeError('{!r} is not a code object'.format(co))
246
246
247 nargs = co.co_argcount
247 nargs = co.co_argcount
248 names = co.co_varnames
248 names = co.co_varnames
249 args = list(names[:nargs])
249 args = list(names[:nargs])
250 step = 0
250 step = 0
251
251
252 # The following acrobatics are for anonymous (tuple) arguments.
252 # The following acrobatics are for anonymous (tuple) arguments.
253 for i in range(nargs):
253 for i in range(nargs):
254 if args[i][:1] in ('', '.'):
254 if args[i][:1] in ('', '.'):
255 stack, remain, count = [], [], []
255 stack, remain, count = [], [], []
256 while step < len(co.co_code):
256 while step < len(co.co_code):
257 op = ord(co.co_code[step])
257 op = ord(co.co_code[step])
258 step = step + 1
258 step = step + 1
259 if op >= dis.HAVE_ARGUMENT:
259 if op >= dis.HAVE_ARGUMENT:
260 opname = dis.opname[op]
260 opname = dis.opname[op]
261 value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
261 value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
262 step = step + 2
262 step = step + 2
263 if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
263 if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
264 remain.append(value)
264 remain.append(value)
265 count.append(value)
265 count.append(value)
266 elif opname in ('STORE_FAST', 'STORE_DEREF'):
266 elif opname in ('STORE_FAST', 'STORE_DEREF'):
267 if op in dis.haslocal:
267 if op in dis.haslocal:
268 stack.append(co.co_varnames[value])
268 stack.append(co.co_varnames[value])
269 elif op in dis.hasfree:
269 elif op in dis.hasfree:
270 stack.append((co.co_cellvars + co.co_freevars)[value])
270 stack.append((co.co_cellvars + co.co_freevars)[value])
271 # Special case for sublists of length 1: def foo((bar))
271 # Special case for sublists of length 1: def foo((bar))
272 # doesn't generate the UNPACK_TUPLE bytecode, so if
272 # doesn't generate the UNPACK_TUPLE bytecode, so if
273 # `remain` is empty here, we have such a sublist.
273 # `remain` is empty here, we have such a sublist.
274 if not remain:
274 if not remain:
275 stack[0] = [stack[0]]
275 stack[0] = [stack[0]]
276 break
276 break
277 else:
277 else:
278 remain[-1] = remain[-1] - 1
278 remain[-1] = remain[-1] - 1
279 while remain[-1] == 0:
279 while remain[-1] == 0:
280 remain.pop()
280 remain.pop()
281 size = count.pop()
281 size = count.pop()
282 stack[-size:] = [stack[-size:]]
282 stack[-size:] = [stack[-size:]]
283 if not remain:
283 if not remain:
284 break
284 break
285 remain[-1] = remain[-1] - 1
285 remain[-1] = remain[-1] - 1
286 if not remain:
286 if not remain:
287 break
287 break
288 args[i] = stack[0]
288 args[i] = stack[0]
289
289
290 varargs = None
290 varargs = None
291 if co.co_flags & inspect.CO_VARARGS:
291 if co.co_flags & inspect.CO_VARARGS:
292 varargs = co.co_varnames[nargs]
292 varargs = co.co_varnames[nargs]
293 nargs = nargs + 1
293 nargs = nargs + 1
294 varkw = None
294 varkw = None
295 if co.co_flags & inspect.CO_VARKEYWORDS:
295 if co.co_flags & inspect.CO_VARKEYWORDS:
296 varkw = co.co_varnames[nargs]
296 varkw = co.co_varnames[nargs]
297 return inspect.Arguments(args, varargs, varkw)
297 return inspect.Arguments(args, varargs, varkw)
298
298
299
299
300 # Monkeypatch inspect to apply our bugfix.
300 # Monkeypatch inspect to apply our bugfix.
301 def with_patch_inspect(f):
301 def with_patch_inspect(f):
302 """decorator for monkeypatching inspect.findsource"""
302 """
303 Deprecated since IPython 6.0
304 decorator for monkeypatching inspect.findsource
305 """
303
306
304 def wrapped(*args, **kwargs):
307 def wrapped(*args, **kwargs):
305 save_findsource = inspect.findsource
308 save_findsource = inspect.findsource
306 save_getargs = inspect.getargs
309 save_getargs = inspect.getargs
307 inspect.findsource = findsource
310 inspect.findsource = findsource
308 inspect.getargs = getargs
311 inspect.getargs = getargs
309 try:
312 try:
310 return f(*args, **kwargs)
313 return f(*args, **kwargs)
311 finally:
314 finally:
312 inspect.findsource = save_findsource
315 inspect.findsource = save_findsource
313 inspect.getargs = save_getargs
316 inspect.getargs = save_getargs
314
317
315 return wrapped
318 return wrapped
316
319
317
320
318 if py3compat.PY3:
319 fixed_getargvalues = inspect.getargvalues
320 else:
321 # Fixes for https://github.com/ipython/ipython/issues/8293
322 # and https://github.com/ipython/ipython/issues/8205.
323 # The relevant bug is caused by failure to correctly handle anonymous tuple
324 # unpacking, which only exists in Python 2.
325 fixed_getargvalues = with_patch_inspect(inspect.getargvalues)
326
327
328 def fix_frame_records_filenames(records):
321 def fix_frame_records_filenames(records):
329 """Try to fix the filenames in each record from inspect.getinnerframes().
322 """Try to fix the filenames in each record from inspect.getinnerframes().
330
323
331 Particularly, modules loaded from within zip files have useless filenames
324 Particularly, modules loaded from within zip files have useless filenames
332 attached to their code object, and inspect.getinnerframes() just uses it.
325 attached to their code object, and inspect.getinnerframes() just uses it.
333 """
326 """
334 fixed_records = []
327 fixed_records = []
335 for frame, filename, line_no, func_name, lines, index in records:
328 for frame, filename, line_no, func_name, lines, index in records:
336 # Look inside the frame's globals dictionary for __file__,
329 # Look inside the frame's globals dictionary for __file__,
337 # which should be better. However, keep Cython filenames since
330 # which should be better. However, keep Cython filenames since
338 # we prefer the source filenames over the compiled .so file.
331 # we prefer the source filenames over the compiled .so file.
339 filename = py3compat.cast_unicode_py2(filename, "utf-8")
332 filename = py3compat.cast_unicode_py2(filename, "utf-8")
340 if not filename.endswith(('.pyx', '.pxd', '.pxi')):
333 if not filename.endswith(('.pyx', '.pxd', '.pxi')):
341 better_fn = frame.f_globals.get('__file__', None)
334 better_fn = frame.f_globals.get('__file__', None)
342 if isinstance(better_fn, str):
335 if isinstance(better_fn, str):
343 # Check the type just in case someone did something weird with
336 # Check the type just in case someone did something weird with
344 # __file__. It might also be None if the error occurred during
337 # __file__. It might also be None if the error occurred during
345 # import.
338 # import.
346 filename = better_fn
339 filename = better_fn
347 fixed_records.append((frame, filename, line_no, func_name, lines, index))
340 fixed_records.append((frame, filename, line_no, func_name, lines, index))
348 return fixed_records
341 return fixed_records
349
342
350
343
351 @with_patch_inspect
344 @with_patch_inspect
352 def _fixed_getinnerframes(etb, context=1, tb_offset=0):
345 def _fixed_getinnerframes(etb, context=1, tb_offset=0):
353 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
346 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
354
347
355 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
348 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
356 # If the error is at the console, don't build any context, since it would
349 # If the error is at the console, don't build any context, since it would
357 # otherwise produce 5 blank lines printed out (there is no file at the
350 # otherwise produce 5 blank lines printed out (there is no file at the
358 # console)
351 # console)
359 rec_check = records[tb_offset:]
352 rec_check = records[tb_offset:]
360 try:
353 try:
361 rname = rec_check[0][1]
354 rname = rec_check[0][1]
362 if rname == '<ipython console>' or rname.endswith('<string>'):
355 if rname == '<ipython console>' or rname.endswith('<string>'):
363 return rec_check
356 return rec_check
364 except IndexError:
357 except IndexError:
365 pass
358 pass
366
359
367 aux = traceback.extract_tb(etb)
360 aux = traceback.extract_tb(etb)
368 assert len(records) == len(aux)
361 assert len(records) == len(aux)
369 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
362 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
370 maybeStart = lnum - 1 - context // 2
363 maybeStart = lnum - 1 - context // 2
371 start = max(maybeStart, 0)
364 start = max(maybeStart, 0)
372 end = start + context
365 end = start + context
373 lines = ulinecache.getlines(file)[start:end]
366 lines = ulinecache.getlines(file)[start:end]
374 buf = list(records[i])
367 buf = list(records[i])
375 buf[LNUM_POS] = lnum
368 buf[LNUM_POS] = lnum
376 buf[INDEX_POS] = lnum - 1 - start
369 buf[INDEX_POS] = lnum - 1 - start
377 buf[LINES_POS] = lines
370 buf[LINES_POS] = lines
378 records[i] = tuple(buf)
371 records[i] = tuple(buf)
379 return records[tb_offset:]
372 return records[tb_offset:]
380
373
381 # Helper function -- largely belongs to VerboseTB, but we need the same
374 # Helper function -- largely belongs to VerboseTB, but we need the same
382 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
375 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
383 # can be recognized properly by ipython.el's py-traceback-line-re
376 # can be recognized properly by ipython.el's py-traceback-line-re
384 # (SyntaxErrors have to be treated specially because they have no traceback)
377 # (SyntaxErrors have to be treated specially because they have no traceback)
385
378
386
379
387 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, _line_format=(lambda x,_:x,None)):
380 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, _line_format=(lambda x,_:x,None)):
388 numbers_width = INDENT_SIZE - 1
381 numbers_width = INDENT_SIZE - 1
389 res = []
382 res = []
390 i = lnum - index
383 i = lnum - index
391
384
392 for line in lines:
385 for line in lines:
393 line = py3compat.cast_unicode(line)
386 line = py3compat.cast_unicode(line)
394
387
395 new_line, err = _line_format(line, 'str')
388 new_line, err = _line_format(line, 'str')
396 if not err: line = new_line
389 if not err: line = new_line
397
390
398 if i == lnum:
391 if i == lnum:
399 # This is the line with the error
392 # This is the line with the error
400 pad = numbers_width - len(str(i))
393 pad = numbers_width - len(str(i))
401 num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
394 num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
402 line = '%s%s%s %s%s' % (Colors.linenoEm, num,
395 line = '%s%s%s %s%s' % (Colors.linenoEm, num,
403 Colors.line, line, Colors.Normal)
396 Colors.line, line, Colors.Normal)
404 else:
397 else:
405 num = '%*s' % (numbers_width, i)
398 num = '%*s' % (numbers_width, i)
406 line = '%s%s%s %s' % (Colors.lineno, num,
399 line = '%s%s%s %s' % (Colors.lineno, num,
407 Colors.Normal, line)
400 Colors.Normal, line)
408
401
409 res.append(line)
402 res.append(line)
410 if lvals and i == lnum:
403 if lvals and i == lnum:
411 res.append(lvals + '\n')
404 res.append(lvals + '\n')
412 i = i + 1
405 i = i + 1
413 return res
406 return res
414
407
415 def is_recursion_error(etype, value, records):
408 def is_recursion_error(etype, value, records):
416 try:
409 try:
417 # RecursionError is new in Python 3.5
410 # RecursionError is new in Python 3.5
418 recursion_error_type = RecursionError
411 recursion_error_type = RecursionError
419 except NameError:
412 except NameError:
420 recursion_error_type = RuntimeError
413 recursion_error_type = RuntimeError
421
414
422 # The default recursion limit is 1000, but some of that will be taken up
415 # The default recursion limit is 1000, but some of that will be taken up
423 # by stack frames in IPython itself. >500 frames probably indicates
416 # by stack frames in IPython itself. >500 frames probably indicates
424 # a recursion error.
417 # a recursion error.
425 return (etype is recursion_error_type) \
418 return (etype is recursion_error_type) \
426 and "recursion" in str(value).lower() \
419 and "recursion" in str(value).lower() \
427 and len(records) > 500
420 and len(records) > 500
428
421
429 def find_recursion(etype, value, records):
422 def find_recursion(etype, value, records):
430 """Identify the repeating stack frames from a RecursionError traceback
423 """Identify the repeating stack frames from a RecursionError traceback
431
424
432 'records' is a list as returned by VerboseTB.get_records()
425 'records' is a list as returned by VerboseTB.get_records()
433
426
434 Returns (last_unique, repeat_length)
427 Returns (last_unique, repeat_length)
435 """
428 """
436 # This involves a bit of guesswork - we want to show enough of the traceback
429 # This involves a bit of guesswork - we want to show enough of the traceback
437 # to indicate where the recursion is occurring. We guess that the innermost
430 # to indicate where the recursion is occurring. We guess that the innermost
438 # quarter of the traceback (250 frames by default) is repeats, and find the
431 # quarter of the traceback (250 frames by default) is repeats, and find the
439 # first frame (from in to out) that looks different.
432 # first frame (from in to out) that looks different.
440 if not is_recursion_error(etype, value, records):
433 if not is_recursion_error(etype, value, records):
441 return len(records), 0
434 return len(records), 0
442
435
443 # Select filename, lineno, func_name to track frames with
436 # Select filename, lineno, func_name to track frames with
444 records = [r[1:4] for r in records]
437 records = [r[1:4] for r in records]
445 inner_frames = records[-(len(records)//4):]
438 inner_frames = records[-(len(records)//4):]
446 frames_repeated = set(inner_frames)
439 frames_repeated = set(inner_frames)
447
440
448 last_seen_at = {}
441 last_seen_at = {}
449 longest_repeat = 0
442 longest_repeat = 0
450 i = len(records)
443 i = len(records)
451 for frame in reversed(records):
444 for frame in reversed(records):
452 i -= 1
445 i -= 1
453 if frame not in frames_repeated:
446 if frame not in frames_repeated:
454 last_unique = i
447 last_unique = i
455 break
448 break
456
449
457 if frame in last_seen_at:
450 if frame in last_seen_at:
458 distance = last_seen_at[frame] - i
451 distance = last_seen_at[frame] - i
459 longest_repeat = max(longest_repeat, distance)
452 longest_repeat = max(longest_repeat, distance)
460
453
461 last_seen_at[frame] = i
454 last_seen_at[frame] = i
462 else:
455 else:
463 last_unique = 0 # The whole traceback was recursion
456 last_unique = 0 # The whole traceback was recursion
464
457
465 return last_unique, longest_repeat
458 return last_unique, longest_repeat
466
459
467 #---------------------------------------------------------------------------
460 #---------------------------------------------------------------------------
468 # Module classes
461 # Module classes
469 class TBTools(colorable.Colorable):
462 class TBTools(colorable.Colorable):
470 """Basic tools used by all traceback printer classes."""
463 """Basic tools used by all traceback printer classes."""
471
464
472 # Number of frames to skip when reporting tracebacks
465 # Number of frames to skip when reporting tracebacks
473 tb_offset = 0
466 tb_offset = 0
474
467
475 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
468 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
476 # Whether to call the interactive pdb debugger after printing
469 # Whether to call the interactive pdb debugger after printing
477 # tracebacks or not
470 # tracebacks or not
478 super(TBTools, self).__init__(parent=parent, config=config)
471 super(TBTools, self).__init__(parent=parent, config=config)
479 self.call_pdb = call_pdb
472 self.call_pdb = call_pdb
480
473
481 # Output stream to write to. Note that we store the original value in
474 # Output stream to write to. Note that we store the original value in
482 # a private attribute and then make the public ostream a property, so
475 # a private attribute and then make the public ostream a property, so
483 # that we can delay accessing sys.stdout until runtime. The way
476 # that we can delay accessing sys.stdout until runtime. The way
484 # things are written now, the sys.stdout object is dynamically managed
477 # things are written now, the sys.stdout object is dynamically managed
485 # so a reference to it should NEVER be stored statically. This
478 # so a reference to it should NEVER be stored statically. This
486 # property approach confines this detail to a single location, and all
479 # property approach confines this detail to a single location, and all
487 # subclasses can simply access self.ostream for writing.
480 # subclasses can simply access self.ostream for writing.
488 self._ostream = ostream
481 self._ostream = ostream
489
482
490 # Create color table
483 # Create color table
491 self.color_scheme_table = exception_colors()
484 self.color_scheme_table = exception_colors()
492
485
493 self.set_colors(color_scheme)
486 self.set_colors(color_scheme)
494 self.old_scheme = color_scheme # save initial value for toggles
487 self.old_scheme = color_scheme # save initial value for toggles
495
488
496 if call_pdb:
489 if call_pdb:
497 self.pdb = debugger.Pdb()
490 self.pdb = debugger.Pdb()
498 else:
491 else:
499 self.pdb = None
492 self.pdb = None
500
493
501 def _get_ostream(self):
494 def _get_ostream(self):
502 """Output stream that exceptions are written to.
495 """Output stream that exceptions are written to.
503
496
504 Valid values are:
497 Valid values are:
505
498
506 - None: the default, which means that IPython will dynamically resolve
499 - None: the default, which means that IPython will dynamically resolve
507 to sys.stdout. This ensures compatibility with most tools, including
500 to sys.stdout. This ensures compatibility with most tools, including
508 Windows (where plain stdout doesn't recognize ANSI escapes).
501 Windows (where plain stdout doesn't recognize ANSI escapes).
509
502
510 - Any object with 'write' and 'flush' attributes.
503 - Any object with 'write' and 'flush' attributes.
511 """
504 """
512 return sys.stdout if self._ostream is None else self._ostream
505 return sys.stdout if self._ostream is None else self._ostream
513
506
514 def _set_ostream(self, val):
507 def _set_ostream(self, val):
515 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
508 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
516 self._ostream = val
509 self._ostream = val
517
510
518 ostream = property(_get_ostream, _set_ostream)
511 ostream = property(_get_ostream, _set_ostream)
519
512
520 def set_colors(self, *args, **kw):
513 def set_colors(self, *args, **kw):
521 """Shorthand access to the color table scheme selector method."""
514 """Shorthand access to the color table scheme selector method."""
522
515
523 # Set own color table
516 # Set own color table
524 self.color_scheme_table.set_active_scheme(*args, **kw)
517 self.color_scheme_table.set_active_scheme(*args, **kw)
525 # for convenience, set Colors to the active scheme
518 # for convenience, set Colors to the active scheme
526 self.Colors = self.color_scheme_table.active_colors
519 self.Colors = self.color_scheme_table.active_colors
527 # Also set colors of debugger
520 # Also set colors of debugger
528 if hasattr(self, 'pdb') and self.pdb is not None:
521 if hasattr(self, 'pdb') and self.pdb is not None:
529 self.pdb.set_colors(*args, **kw)
522 self.pdb.set_colors(*args, **kw)
530
523
531 def color_toggle(self):
524 def color_toggle(self):
532 """Toggle between the currently active color scheme and NoColor."""
525 """Toggle between the currently active color scheme and NoColor."""
533
526
534 if self.color_scheme_table.active_scheme_name == 'NoColor':
527 if self.color_scheme_table.active_scheme_name == 'NoColor':
535 self.color_scheme_table.set_active_scheme(self.old_scheme)
528 self.color_scheme_table.set_active_scheme(self.old_scheme)
536 self.Colors = self.color_scheme_table.active_colors
529 self.Colors = self.color_scheme_table.active_colors
537 else:
530 else:
538 self.old_scheme = self.color_scheme_table.active_scheme_name
531 self.old_scheme = self.color_scheme_table.active_scheme_name
539 self.color_scheme_table.set_active_scheme('NoColor')
532 self.color_scheme_table.set_active_scheme('NoColor')
540 self.Colors = self.color_scheme_table.active_colors
533 self.Colors = self.color_scheme_table.active_colors
541
534
542 def stb2text(self, stb):
535 def stb2text(self, stb):
543 """Convert a structured traceback (a list) to a string."""
536 """Convert a structured traceback (a list) to a string."""
544 return '\n'.join(stb)
537 return '\n'.join(stb)
545
538
546 def text(self, etype, value, tb, tb_offset=None, context=5):
539 def text(self, etype, value, tb, tb_offset=None, context=5):
547 """Return formatted traceback.
540 """Return formatted traceback.
548
541
549 Subclasses may override this if they add extra arguments.
542 Subclasses may override this if they add extra arguments.
550 """
543 """
551 tb_list = self.structured_traceback(etype, value, tb,
544 tb_list = self.structured_traceback(etype, value, tb,
552 tb_offset, context)
545 tb_offset, context)
553 return self.stb2text(tb_list)
546 return self.stb2text(tb_list)
554
547
555 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
548 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
556 context=5, mode=None):
549 context=5, mode=None):
557 """Return a list of traceback frames.
550 """Return a list of traceback frames.
558
551
559 Must be implemented by each class.
552 Must be implemented by each class.
560 """
553 """
561 raise NotImplementedError()
554 raise NotImplementedError()
562
555
563
556
564 #---------------------------------------------------------------------------
557 #---------------------------------------------------------------------------
565 class ListTB(TBTools):
558 class ListTB(TBTools):
566 """Print traceback information from a traceback list, with optional color.
559 """Print traceback information from a traceback list, with optional color.
567
560
568 Calling requires 3 arguments: (etype, evalue, elist)
561 Calling requires 3 arguments: (etype, evalue, elist)
569 as would be obtained by::
562 as would be obtained by::
570
563
571 etype, evalue, tb = sys.exc_info()
564 etype, evalue, tb = sys.exc_info()
572 if tb:
565 if tb:
573 elist = traceback.extract_tb(tb)
566 elist = traceback.extract_tb(tb)
574 else:
567 else:
575 elist = None
568 elist = None
576
569
577 It can thus be used by programs which need to process the traceback before
570 It can thus be used by programs which need to process the traceback before
578 printing (such as console replacements based on the code module from the
571 printing (such as console replacements based on the code module from the
579 standard library).
572 standard library).
580
573
581 Because they are meant to be called without a full traceback (only a
574 Because they are meant to be called without a full traceback (only a
582 list), instances of this class can't call the interactive pdb debugger."""
575 list), instances of this class can't call the interactive pdb debugger."""
583
576
584 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
577 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
585 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
578 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
586 ostream=ostream, parent=parent,config=config)
579 ostream=ostream, parent=parent,config=config)
587
580
588 def __call__(self, etype, value, elist):
581 def __call__(self, etype, value, elist):
589 self.ostream.flush()
582 self.ostream.flush()
590 self.ostream.write(self.text(etype, value, elist))
583 self.ostream.write(self.text(etype, value, elist))
591 self.ostream.write('\n')
584 self.ostream.write('\n')
592
585
593 def structured_traceback(self, etype, value, elist, tb_offset=None,
586 def structured_traceback(self, etype, value, elist, tb_offset=None,
594 context=5):
587 context=5):
595 """Return a color formatted string with the traceback info.
588 """Return a color formatted string with the traceback info.
596
589
597 Parameters
590 Parameters
598 ----------
591 ----------
599 etype : exception type
592 etype : exception type
600 Type of the exception raised.
593 Type of the exception raised.
601
594
602 value : object
595 value : object
603 Data stored in the exception
596 Data stored in the exception
604
597
605 elist : list
598 elist : list
606 List of frames, see class docstring for details.
599 List of frames, see class docstring for details.
607
600
608 tb_offset : int, optional
601 tb_offset : int, optional
609 Number of frames in the traceback to skip. If not given, the
602 Number of frames in the traceback to skip. If not given, the
610 instance value is used (set in constructor).
603 instance value is used (set in constructor).
611
604
612 context : int, optional
605 context : int, optional
613 Number of lines of context information to print.
606 Number of lines of context information to print.
614
607
615 Returns
608 Returns
616 -------
609 -------
617 String with formatted exception.
610 String with formatted exception.
618 """
611 """
619 tb_offset = self.tb_offset if tb_offset is None else tb_offset
612 tb_offset = self.tb_offset if tb_offset is None else tb_offset
620 Colors = self.Colors
613 Colors = self.Colors
621 out_list = []
614 out_list = []
622 if elist:
615 if elist:
623
616
624 if tb_offset and len(elist) > tb_offset:
617 if tb_offset and len(elist) > tb_offset:
625 elist = elist[tb_offset:]
618 elist = elist[tb_offset:]
626
619
627 out_list.append('Traceback %s(most recent call last)%s:' %
620 out_list.append('Traceback %s(most recent call last)%s:' %
628 (Colors.normalEm, Colors.Normal) + '\n')
621 (Colors.normalEm, Colors.Normal) + '\n')
629 out_list.extend(self._format_list(elist))
622 out_list.extend(self._format_list(elist))
630 # The exception info should be a single entry in the list.
623 # The exception info should be a single entry in the list.
631 lines = ''.join(self._format_exception_only(etype, value))
624 lines = ''.join(self._format_exception_only(etype, value))
632 out_list.append(lines)
625 out_list.append(lines)
633
626
634 # Note: this code originally read:
627 # Note: this code originally read:
635
628
636 ## for line in lines[:-1]:
629 ## for line in lines[:-1]:
637 ## out_list.append(" "+line)
630 ## out_list.append(" "+line)
638 ## out_list.append(lines[-1])
631 ## out_list.append(lines[-1])
639
632
640 # This means it was indenting everything but the last line by a little
633 # This means it was indenting everything but the last line by a little
641 # bit. I've disabled this for now, but if we see ugliness somewhere we
634 # bit. I've disabled this for now, but if we see ugliness somewhere we
642 # can restore it.
635 # can restore it.
643
636
644 return out_list
637 return out_list
645
638
646 def _format_list(self, extracted_list):
639 def _format_list(self, extracted_list):
647 """Format a list of traceback entry tuples for printing.
640 """Format a list of traceback entry tuples for printing.
648
641
649 Given a list of tuples as returned by extract_tb() or
642 Given a list of tuples as returned by extract_tb() or
650 extract_stack(), return a list of strings ready for printing.
643 extract_stack(), return a list of strings ready for printing.
651 Each string in the resulting list corresponds to the item with the
644 Each string in the resulting list corresponds to the item with the
652 same index in the argument list. Each string ends in a newline;
645 same index in the argument list. Each string ends in a newline;
653 the strings may contain internal newlines as well, for those items
646 the strings may contain internal newlines as well, for those items
654 whose source text line is not None.
647 whose source text line is not None.
655
648
656 Lifted almost verbatim from traceback.py
649 Lifted almost verbatim from traceback.py
657 """
650 """
658
651
659 Colors = self.Colors
652 Colors = self.Colors
660 list = []
653 list = []
661 for filename, lineno, name, line in extracted_list[:-1]:
654 for filename, lineno, name, line in extracted_list[:-1]:
662 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
655 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
663 (Colors.filename, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.Normal,
656 (Colors.filename, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.Normal,
664 Colors.lineno, lineno, Colors.Normal,
657 Colors.lineno, lineno, Colors.Normal,
665 Colors.name, py3compat.cast_unicode_py2(name, "utf-8"), Colors.Normal)
658 Colors.name, py3compat.cast_unicode_py2(name, "utf-8"), Colors.Normal)
666 if line:
659 if line:
667 item += ' %s\n' % line.strip()
660 item += ' %s\n' % line.strip()
668 list.append(item)
661 list.append(item)
669 # Emphasize the last entry
662 # Emphasize the last entry
670 filename, lineno, name, line = extracted_list[-1]
663 filename, lineno, name, line = extracted_list[-1]
671 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
664 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
672 (Colors.normalEm,
665 (Colors.normalEm,
673 Colors.filenameEm, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.normalEm,
666 Colors.filenameEm, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.normalEm,
674 Colors.linenoEm, lineno, Colors.normalEm,
667 Colors.linenoEm, lineno, Colors.normalEm,
675 Colors.nameEm, py3compat.cast_unicode_py2(name, "utf-8"), Colors.normalEm,
668 Colors.nameEm, py3compat.cast_unicode_py2(name, "utf-8"), Colors.normalEm,
676 Colors.Normal)
669 Colors.Normal)
677 if line:
670 if line:
678 item += '%s %s%s\n' % (Colors.line, line.strip(),
671 item += '%s %s%s\n' % (Colors.line, line.strip(),
679 Colors.Normal)
672 Colors.Normal)
680 list.append(item)
673 list.append(item)
681 return list
674 return list
682
675
683 def _format_exception_only(self, etype, value):
676 def _format_exception_only(self, etype, value):
684 """Format the exception part of a traceback.
677 """Format the exception part of a traceback.
685
678
686 The arguments are the exception type and value such as given by
679 The arguments are the exception type and value such as given by
687 sys.exc_info()[:2]. The return value is a list of strings, each ending
680 sys.exc_info()[:2]. The return value is a list of strings, each ending
688 in a newline. Normally, the list contains a single string; however,
681 in a newline. Normally, the list contains a single string; however,
689 for SyntaxError exceptions, it contains several lines that (when
682 for SyntaxError exceptions, it contains several lines that (when
690 printed) display detailed information about where the syntax error
683 printed) display detailed information about where the syntax error
691 occurred. The message indicating which exception occurred is the
684 occurred. The message indicating which exception occurred is the
692 always last string in the list.
685 always last string in the list.
693
686
694 Also lifted nearly verbatim from traceback.py
687 Also lifted nearly verbatim from traceback.py
695 """
688 """
696 have_filedata = False
689 have_filedata = False
697 Colors = self.Colors
690 Colors = self.Colors
698 list = []
691 list = []
699 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
692 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
700 if value is None:
693 if value is None:
701 # Not sure if this can still happen in Python 2.6 and above
694 # Not sure if this can still happen in Python 2.6 and above
702 list.append(stype + '\n')
695 list.append(stype + '\n')
703 else:
696 else:
704 if issubclass(etype, SyntaxError):
697 if issubclass(etype, SyntaxError):
705 have_filedata = True
698 have_filedata = True
706 if not value.filename: value.filename = "<string>"
699 if not value.filename: value.filename = "<string>"
707 if value.lineno:
700 if value.lineno:
708 lineno = value.lineno
701 lineno = value.lineno
709 textline = ulinecache.getline(value.filename, value.lineno)
702 textline = ulinecache.getline(value.filename, value.lineno)
710 else:
703 else:
711 lineno = 'unknown'
704 lineno = 'unknown'
712 textline = ''
705 textline = ''
713 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
706 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
714 (Colors.normalEm,
707 (Colors.normalEm,
715 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
708 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
716 Colors.linenoEm, lineno, Colors.Normal ))
709 Colors.linenoEm, lineno, Colors.Normal ))
717 if textline == '':
710 if textline == '':
718 textline = py3compat.cast_unicode(value.text, "utf-8")
711 textline = py3compat.cast_unicode(value.text, "utf-8")
719
712
720 if textline is not None:
713 if textline is not None:
721 i = 0
714 i = 0
722 while i < len(textline) and textline[i].isspace():
715 while i < len(textline) and textline[i].isspace():
723 i += 1
716 i += 1
724 list.append('%s %s%s\n' % (Colors.line,
717 list.append('%s %s%s\n' % (Colors.line,
725 textline.strip(),
718 textline.strip(),
726 Colors.Normal))
719 Colors.Normal))
727 if value.offset is not None:
720 if value.offset is not None:
728 s = ' '
721 s = ' '
729 for c in textline[i:value.offset - 1]:
722 for c in textline[i:value.offset - 1]:
730 if c.isspace():
723 if c.isspace():
731 s += c
724 s += c
732 else:
725 else:
733 s += ' '
726 s += ' '
734 list.append('%s%s^%s\n' % (Colors.caret, s,
727 list.append('%s%s^%s\n' % (Colors.caret, s,
735 Colors.Normal))
728 Colors.Normal))
736
729
737 try:
730 try:
738 s = value.msg
731 s = value.msg
739 except Exception:
732 except Exception:
740 s = self._some_str(value)
733 s = self._some_str(value)
741 if s:
734 if s:
742 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
735 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
743 Colors.Normal, s))
736 Colors.Normal, s))
744 else:
737 else:
745 list.append('%s\n' % stype)
738 list.append('%s\n' % stype)
746
739
747 # sync with user hooks
740 # sync with user hooks
748 if have_filedata:
741 if have_filedata:
749 ipinst = get_ipython()
742 ipinst = get_ipython()
750 if ipinst is not None:
743 if ipinst is not None:
751 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
744 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
752
745
753 return list
746 return list
754
747
755 def get_exception_only(self, etype, value):
748 def get_exception_only(self, etype, value):
756 """Only print the exception type and message, without a traceback.
749 """Only print the exception type and message, without a traceback.
757
750
758 Parameters
751 Parameters
759 ----------
752 ----------
760 etype : exception type
753 etype : exception type
761 value : exception value
754 value : exception value
762 """
755 """
763 return ListTB.structured_traceback(self, etype, value, [])
756 return ListTB.structured_traceback(self, etype, value, [])
764
757
765 def show_exception_only(self, etype, evalue):
758 def show_exception_only(self, etype, evalue):
766 """Only print the exception type and message, without a traceback.
759 """Only print the exception type and message, without a traceback.
767
760
768 Parameters
761 Parameters
769 ----------
762 ----------
770 etype : exception type
763 etype : exception type
771 value : exception value
764 value : exception value
772 """
765 """
773 # This method needs to use __call__ from *this* class, not the one from
766 # This method needs to use __call__ from *this* class, not the one from
774 # a subclass whose signature or behavior may be different
767 # a subclass whose signature or behavior may be different
775 ostream = self.ostream
768 ostream = self.ostream
776 ostream.flush()
769 ostream.flush()
777 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
770 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
778 ostream.flush()
771 ostream.flush()
779
772
780 def _some_str(self, value):
773 def _some_str(self, value):
781 # Lifted from traceback.py
774 # Lifted from traceback.py
782 try:
775 try:
783 return py3compat.cast_unicode(str(value))
776 return py3compat.cast_unicode(str(value))
784 except:
777 except:
785 return u'<unprintable %s object>' % type(value).__name__
778 return u'<unprintable %s object>' % type(value).__name__
786
779
787
780
788 #----------------------------------------------------------------------------
781 #----------------------------------------------------------------------------
789 class VerboseTB(TBTools):
782 class VerboseTB(TBTools):
790 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
783 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
791 of HTML. Requires inspect and pydoc. Crazy, man.
784 of HTML. Requires inspect and pydoc. Crazy, man.
792
785
793 Modified version which optionally strips the topmost entries from the
786 Modified version which optionally strips the topmost entries from the
794 traceback, to be used with alternate interpreters (because their own code
787 traceback, to be used with alternate interpreters (because their own code
795 would appear in the traceback)."""
788 would appear in the traceback)."""
796
789
797 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
790 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
798 tb_offset=0, long_header=False, include_vars=True,
791 tb_offset=0, long_header=False, include_vars=True,
799 check_cache=None, debugger_cls = None,
792 check_cache=None, debugger_cls = None,
800 parent=None, config=None):
793 parent=None, config=None):
801 """Specify traceback offset, headers and color scheme.
794 """Specify traceback offset, headers and color scheme.
802
795
803 Define how many frames to drop from the tracebacks. Calling it with
796 Define how many frames to drop from the tracebacks. Calling it with
804 tb_offset=1 allows use of this handler in interpreters which will have
797 tb_offset=1 allows use of this handler in interpreters which will have
805 their own code at the top of the traceback (VerboseTB will first
798 their own code at the top of the traceback (VerboseTB will first
806 remove that frame before printing the traceback info)."""
799 remove that frame before printing the traceback info)."""
807 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
800 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
808 ostream=ostream, parent=parent, config=config)
801 ostream=ostream, parent=parent, config=config)
809 self.tb_offset = tb_offset
802 self.tb_offset = tb_offset
810 self.long_header = long_header
803 self.long_header = long_header
811 self.include_vars = include_vars
804 self.include_vars = include_vars
812 # By default we use linecache.checkcache, but the user can provide a
805 # By default we use linecache.checkcache, but the user can provide a
813 # different check_cache implementation. This is used by the IPython
806 # different check_cache implementation. This is used by the IPython
814 # kernel to provide tracebacks for interactive code that is cached,
807 # kernel to provide tracebacks for interactive code that is cached,
815 # by a compiler instance that flushes the linecache but preserves its
808 # by a compiler instance that flushes the linecache but preserves its
816 # own code cache.
809 # own code cache.
817 if check_cache is None:
810 if check_cache is None:
818 check_cache = linecache.checkcache
811 check_cache = linecache.checkcache
819 self.check_cache = check_cache
812 self.check_cache = check_cache
820
813
821 self.debugger_cls = debugger_cls or debugger.Pdb
814 self.debugger_cls = debugger_cls or debugger.Pdb
822
815
823 def format_records(self, records, last_unique, recursion_repeat):
816 def format_records(self, records, last_unique, recursion_repeat):
824 """Format the stack frames of the traceback"""
817 """Format the stack frames of the traceback"""
825 frames = []
818 frames = []
826 for r in records[:last_unique+recursion_repeat+1]:
819 for r in records[:last_unique+recursion_repeat+1]:
827 #print '*** record:',file,lnum,func,lines,index # dbg
820 #print '*** record:',file,lnum,func,lines,index # dbg
828 frames.append(self.format_record(*r))
821 frames.append(self.format_record(*r))
829
822
830 if recursion_repeat:
823 if recursion_repeat:
831 frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat)
824 frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat)
832 frames.append(self.format_record(*records[last_unique+recursion_repeat+1]))
825 frames.append(self.format_record(*records[last_unique+recursion_repeat+1]))
833
826
834 return frames
827 return frames
835
828
836 def format_record(self, frame, file, lnum, func, lines, index):
829 def format_record(self, frame, file, lnum, func, lines, index):
837 """Format a single stack frame"""
830 """Format a single stack frame"""
838 Colors = self.Colors # just a shorthand + quicker name lookup
831 Colors = self.Colors # just a shorthand + quicker name lookup
839 ColorsNormal = Colors.Normal # used a lot
832 ColorsNormal = Colors.Normal # used a lot
840 col_scheme = self.color_scheme_table.active_scheme_name
833 col_scheme = self.color_scheme_table.active_scheme_name
841 indent = ' ' * INDENT_SIZE
834 indent = ' ' * INDENT_SIZE
842 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
835 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
843 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
836 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
844 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
837 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
845 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
838 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
846 ColorsNormal)
839 ColorsNormal)
847 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
840 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
848 (Colors.vName, Colors.valEm, ColorsNormal)
841 (Colors.vName, Colors.valEm, ColorsNormal)
849 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
842 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
850 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
843 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
851 Colors.vName, ColorsNormal)
844 Colors.vName, ColorsNormal)
852 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
845 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
853
846
854 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
847 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
855 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line,
848 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line,
856 ColorsNormal)
849 ColorsNormal)
857
850
858 abspath = os.path.abspath
851 abspath = os.path.abspath
859
852
860
853
861 if not file:
854 if not file:
862 file = '?'
855 file = '?'
863 elif file.startswith(str("<")) and file.endswith(str(">")):
856 elif file.startswith(str("<")) and file.endswith(str(">")):
864 # Not a real filename, no problem...
857 # Not a real filename, no problem...
865 pass
858 pass
866 elif not os.path.isabs(file):
859 elif not os.path.isabs(file):
867 # Try to make the filename absolute by trying all
860 # Try to make the filename absolute by trying all
868 # sys.path entries (which is also what linecache does)
861 # sys.path entries (which is also what linecache does)
869 for dirname in sys.path:
862 for dirname in sys.path:
870 try:
863 try:
871 fullname = os.path.join(dirname, file)
864 fullname = os.path.join(dirname, file)
872 if os.path.isfile(fullname):
865 if os.path.isfile(fullname):
873 file = os.path.abspath(fullname)
866 file = os.path.abspath(fullname)
874 break
867 break
875 except Exception:
868 except Exception:
876 # Just in case that sys.path contains very
869 # Just in case that sys.path contains very
877 # strange entries...
870 # strange entries...
878 pass
871 pass
879
872
880 file = py3compat.cast_unicode(file, util_path.fs_encoding)
873 file = py3compat.cast_unicode(file, util_path.fs_encoding)
881 link = tpl_link % file
874 link = tpl_link % file
882 args, varargs, varkw, locals = fixed_getargvalues(frame)
875 args, varargs, varkw, locals = inspect.getargvalues(frame)
883
876
884 if func == '?':
877 if func == '?':
885 call = ''
878 call = ''
886 else:
879 else:
887 # Decide whether to include variable details or not
880 # Decide whether to include variable details or not
888 var_repr = self.include_vars and eqrepr or nullrepr
881 var_repr = self.include_vars and eqrepr or nullrepr
889 try:
882 try:
890 call = tpl_call % (func, inspect.formatargvalues(args,
883 call = tpl_call % (func, inspect.formatargvalues(args,
891 varargs, varkw,
884 varargs, varkw,
892 locals, formatvalue=var_repr))
885 locals, formatvalue=var_repr))
893 except KeyError:
886 except KeyError:
894 # This happens in situations like errors inside generator
887 # This happens in situations like errors inside generator
895 # expressions, where local variables are listed in the
888 # expressions, where local variables are listed in the
896 # line, but can't be extracted from the frame. I'm not
889 # line, but can't be extracted from the frame. I'm not
897 # 100% sure this isn't actually a bug in inspect itself,
890 # 100% sure this isn't actually a bug in inspect itself,
898 # but since there's no info for us to compute with, the
891 # but since there's no info for us to compute with, the
899 # best we can do is report the failure and move on. Here
892 # best we can do is report the failure and move on. Here
900 # we must *not* call any traceback construction again,
893 # we must *not* call any traceback construction again,
901 # because that would mess up use of %debug later on. So we
894 # because that would mess up use of %debug later on. So we
902 # simply report the failure and move on. The only
895 # simply report the failure and move on. The only
903 # limitation will be that this frame won't have locals
896 # limitation will be that this frame won't have locals
904 # listed in the call signature. Quite subtle problem...
897 # listed in the call signature. Quite subtle problem...
905 # I can't think of a good way to validate this in a unit
898 # I can't think of a good way to validate this in a unit
906 # test, but running a script consisting of:
899 # test, but running a script consisting of:
907 # dict( (k,v.strip()) for (k,v) in range(10) )
900 # dict( (k,v.strip()) for (k,v) in range(10) )
908 # will illustrate the error, if this exception catch is
901 # will illustrate the error, if this exception catch is
909 # disabled.
902 # disabled.
910 call = tpl_call_fail % func
903 call = tpl_call_fail % func
911
904
912 # Don't attempt to tokenize binary files.
905 # Don't attempt to tokenize binary files.
913 if file.endswith(('.so', '.pyd', '.dll')):
906 if file.endswith(('.so', '.pyd', '.dll')):
914 return '%s %s\n' % (link, call)
907 return '%s %s\n' % (link, call)
915
908
916 elif file.endswith(('.pyc', '.pyo')):
909 elif file.endswith(('.pyc', '.pyo')):
917 # Look up the corresponding source file.
910 # Look up the corresponding source file.
918 try:
911 try:
919 file = openpy.source_from_cache(file)
912 file = openpy.source_from_cache(file)
920 except ValueError:
913 except ValueError:
921 # Failed to get the source file for some reason
914 # Failed to get the source file for some reason
922 # E.g. https://github.com/ipython/ipython/issues/9486
915 # E.g. https://github.com/ipython/ipython/issues/9486
923 return '%s %s\n' % (link, call)
916 return '%s %s\n' % (link, call)
924
917
925 def linereader(file=file, lnum=[lnum], getline=ulinecache.getline):
918 def linereader(file=file, lnum=[lnum], getline=ulinecache.getline):
926 line = getline(file, lnum[0])
919 line = getline(file, lnum[0])
927 lnum[0] += 1
920 lnum[0] += 1
928 return line
921 return line
929
922
930 # Build the list of names on this line of code where the exception
923 # Build the list of names on this line of code where the exception
931 # occurred.
924 # occurred.
932 try:
925 try:
933 names = []
926 names = []
934 name_cont = False
927 name_cont = False
935
928
936 for token_type, token, start, end, line in generate_tokens(linereader):
929 for token_type, token, start, end, line in generate_tokens(linereader):
937 # build composite names
930 # build composite names
938 if token_type == tokenize.NAME and token not in keyword.kwlist:
931 if token_type == tokenize.NAME and token not in keyword.kwlist:
939 if name_cont:
932 if name_cont:
940 # Continuation of a dotted name
933 # Continuation of a dotted name
941 try:
934 try:
942 names[-1].append(token)
935 names[-1].append(token)
943 except IndexError:
936 except IndexError:
944 names.append([token])
937 names.append([token])
945 name_cont = False
938 name_cont = False
946 else:
939 else:
947 # Regular new names. We append everything, the caller
940 # Regular new names. We append everything, the caller
948 # will be responsible for pruning the list later. It's
941 # will be responsible for pruning the list later. It's
949 # very tricky to try to prune as we go, b/c composite
942 # very tricky to try to prune as we go, b/c composite
950 # names can fool us. The pruning at the end is easy
943 # names can fool us. The pruning at the end is easy
951 # to do (or the caller can print a list with repeated
944 # to do (or the caller can print a list with repeated
952 # names if so desired.
945 # names if so desired.
953 names.append([token])
946 names.append([token])
954 elif token == '.':
947 elif token == '.':
955 name_cont = True
948 name_cont = True
956 elif token_type == tokenize.NEWLINE:
949 elif token_type == tokenize.NEWLINE:
957 break
950 break
958
951
959 except (IndexError, UnicodeDecodeError, SyntaxError):
952 except (IndexError, UnicodeDecodeError, SyntaxError):
960 # signals exit of tokenizer
953 # signals exit of tokenizer
961 # SyntaxError can occur if the file is not actually Python
954 # SyntaxError can occur if the file is not actually Python
962 # - see gh-6300
955 # - see gh-6300
963 pass
956 pass
964 except tokenize.TokenError as msg:
957 except tokenize.TokenError as msg:
965 _m = ("An unexpected error occurred while tokenizing input\n"
958 _m = ("An unexpected error occurred while tokenizing input\n"
966 "The following traceback may be corrupted or invalid\n"
959 "The following traceback may be corrupted or invalid\n"
967 "The error message is: %s\n" % msg)
960 "The error message is: %s\n" % msg)
968 error(_m)
961 error(_m)
969
962
970 # Join composite names (e.g. "dict.fromkeys")
963 # Join composite names (e.g. "dict.fromkeys")
971 names = ['.'.join(n) for n in names]
964 names = ['.'.join(n) for n in names]
972 # prune names list of duplicates, but keep the right order
965 # prune names list of duplicates, but keep the right order
973 unique_names = uniq_stable(names)
966 unique_names = uniq_stable(names)
974
967
975 # Start loop over vars
968 # Start loop over vars
976 lvals = []
969 lvals = []
977 if self.include_vars:
970 if self.include_vars:
978 for name_full in unique_names:
971 for name_full in unique_names:
979 name_base = name_full.split('.', 1)[0]
972 name_base = name_full.split('.', 1)[0]
980 if name_base in frame.f_code.co_varnames:
973 if name_base in frame.f_code.co_varnames:
981 if name_base in locals:
974 if name_base in locals:
982 try:
975 try:
983 value = repr(eval(name_full, locals))
976 value = repr(eval(name_full, locals))
984 except:
977 except:
985 value = undefined
978 value = undefined
986 else:
979 else:
987 value = undefined
980 value = undefined
988 name = tpl_local_var % name_full
981 name = tpl_local_var % name_full
989 else:
982 else:
990 if name_base in frame.f_globals:
983 if name_base in frame.f_globals:
991 try:
984 try:
992 value = repr(eval(name_full, frame.f_globals))
985 value = repr(eval(name_full, frame.f_globals))
993 except:
986 except:
994 value = undefined
987 value = undefined
995 else:
988 else:
996 value = undefined
989 value = undefined
997 name = tpl_global_var % name_full
990 name = tpl_global_var % name_full
998 lvals.append(tpl_name_val % (name, value))
991 lvals.append(tpl_name_val % (name, value))
999 if lvals:
992 if lvals:
1000 lvals = '%s%s' % (indent, em_normal.join(lvals))
993 lvals = '%s%s' % (indent, em_normal.join(lvals))
1001 else:
994 else:
1002 lvals = ''
995 lvals = ''
1003
996
1004 level = '%s %s\n' % (link, call)
997 level = '%s %s\n' % (link, call)
1005
998
1006 if index is None:
999 if index is None:
1007 return level
1000 return level
1008 else:
1001 else:
1009 _line_format = PyColorize.Parser(style=col_scheme, parent=self).format2
1002 _line_format = PyColorize.Parser(style=col_scheme, parent=self).format2
1010 return '%s%s' % (level, ''.join(
1003 return '%s%s' % (level, ''.join(
1011 _format_traceback_lines(lnum, index, lines, Colors, lvals,
1004 _format_traceback_lines(lnum, index, lines, Colors, lvals,
1012 _line_format)))
1005 _line_format)))
1013
1006
1014 def prepare_chained_exception_message(self, cause):
1007 def prepare_chained_exception_message(self, cause):
1015 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
1008 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
1016 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
1009 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
1017
1010
1018 if cause:
1011 if cause:
1019 message = [[direct_cause]]
1012 message = [[direct_cause]]
1020 else:
1013 else:
1021 message = [[exception_during_handling]]
1014 message = [[exception_during_handling]]
1022 return message
1015 return message
1023
1016
1024 def prepare_header(self, etype, long_version=False):
1017 def prepare_header(self, etype, long_version=False):
1025 colors = self.Colors # just a shorthand + quicker name lookup
1018 colors = self.Colors # just a shorthand + quicker name lookup
1026 colorsnormal = colors.Normal # used a lot
1019 colorsnormal = colors.Normal # used a lot
1027 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
1020 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
1028 width = min(75, get_terminal_size()[0])
1021 width = min(75, get_terminal_size()[0])
1029 if long_version:
1022 if long_version:
1030 # Header with the exception type, python version, and date
1023 # Header with the exception type, python version, and date
1031 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
1024 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
1032 date = time.ctime(time.time())
1025 date = time.ctime(time.time())
1033
1026
1034 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
1027 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
1035 exc, ' ' * (width - len(str(etype)) - len(pyver)),
1028 exc, ' ' * (width - len(str(etype)) - len(pyver)),
1036 pyver, date.rjust(width) )
1029 pyver, date.rjust(width) )
1037 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
1030 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
1038 "\ncalls leading up to the error, with the most recent (innermost) call last."
1031 "\ncalls leading up to the error, with the most recent (innermost) call last."
1039 else:
1032 else:
1040 # Simplified header
1033 # Simplified header
1041 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
1034 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
1042 rjust(width - len(str(etype))) )
1035 rjust(width - len(str(etype))) )
1043
1036
1044 return head
1037 return head
1045
1038
1046 def format_exception(self, etype, evalue):
1039 def format_exception(self, etype, evalue):
1047 colors = self.Colors # just a shorthand + quicker name lookup
1040 colors = self.Colors # just a shorthand + quicker name lookup
1048 colorsnormal = colors.Normal # used a lot
1041 colorsnormal = colors.Normal # used a lot
1049 indent = ' ' * INDENT_SIZE
1042 indent = ' ' * INDENT_SIZE
1050 # Get (safely) a string form of the exception info
1043 # Get (safely) a string form of the exception info
1051 try:
1044 try:
1052 etype_str, evalue_str = map(str, (etype, evalue))
1045 etype_str, evalue_str = map(str, (etype, evalue))
1053 except:
1046 except:
1054 # User exception is improperly defined.
1047 # User exception is improperly defined.
1055 etype, evalue = str, sys.exc_info()[:2]
1048 etype, evalue = str, sys.exc_info()[:2]
1056 etype_str, evalue_str = map(str, (etype, evalue))
1049 etype_str, evalue_str = map(str, (etype, evalue))
1057 # ... and format it
1050 # ... and format it
1058 return ['%s%s%s: %s' % (colors.excName, etype_str,
1051 return ['%s%s%s: %s' % (colors.excName, etype_str,
1059 colorsnormal, py3compat.cast_unicode(evalue_str))]
1052 colorsnormal, py3compat.cast_unicode(evalue_str))]
1060
1053
1061 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
1054 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
1062 """Formats the header, traceback and exception message for a single exception.
1055 """Formats the header, traceback and exception message for a single exception.
1063
1056
1064 This may be called multiple times by Python 3 exception chaining
1057 This may be called multiple times by Python 3 exception chaining
1065 (PEP 3134).
1058 (PEP 3134).
1066 """
1059 """
1067 # some locals
1060 # some locals
1068 orig_etype = etype
1061 orig_etype = etype
1069 try:
1062 try:
1070 etype = etype.__name__
1063 etype = etype.__name__
1071 except AttributeError:
1064 except AttributeError:
1072 pass
1065 pass
1073
1066
1074 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1067 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1075 head = self.prepare_header(etype, self.long_header)
1068 head = self.prepare_header(etype, self.long_header)
1076 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
1069 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
1077
1070
1078 if records is None:
1071 if records is None:
1079 return ""
1072 return ""
1080
1073
1081 last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
1074 last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
1082
1075
1083 frames = self.format_records(records, last_unique, recursion_repeat)
1076 frames = self.format_records(records, last_unique, recursion_repeat)
1084
1077
1085 formatted_exception = self.format_exception(etype, evalue)
1078 formatted_exception = self.format_exception(etype, evalue)
1086 if records:
1079 if records:
1087 filepath, lnum = records[-1][1:3]
1080 filepath, lnum = records[-1][1:3]
1088 filepath = os.path.abspath(filepath)
1081 filepath = os.path.abspath(filepath)
1089 ipinst = get_ipython()
1082 ipinst = get_ipython()
1090 if ipinst is not None:
1083 if ipinst is not None:
1091 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
1084 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
1092
1085
1093 return [[head] + frames + [''.join(formatted_exception[0])]]
1086 return [[head] + frames + [''.join(formatted_exception[0])]]
1094
1087
1095 def get_records(self, etb, number_of_lines_of_context, tb_offset):
1088 def get_records(self, etb, number_of_lines_of_context, tb_offset):
1096 try:
1089 try:
1097 # Try the default getinnerframes and Alex's: Alex's fixes some
1090 # Try the default getinnerframes and Alex's: Alex's fixes some
1098 # problems, but it generates empty tracebacks for console errors
1091 # problems, but it generates empty tracebacks for console errors
1099 # (5 blanks lines) where none should be returned.
1092 # (5 blanks lines) where none should be returned.
1100 return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
1093 return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
1101 except UnicodeDecodeError:
1094 except UnicodeDecodeError:
1102 # This can occur if a file's encoding magic comment is wrong.
1095 # This can occur if a file's encoding magic comment is wrong.
1103 # I can't see a way to recover without duplicating a bunch of code
1096 # I can't see a way to recover without duplicating a bunch of code
1104 # from the stdlib traceback module. --TK
1097 # from the stdlib traceback module. --TK
1105 error('\nUnicodeDecodeError while processing traceback.\n')
1098 error('\nUnicodeDecodeError while processing traceback.\n')
1106 return None
1099 return None
1107 except:
1100 except:
1108 # FIXME: I've been getting many crash reports from python 2.3
1101 # FIXME: I've been getting many crash reports from python 2.3
1109 # users, traceable to inspect.py. If I can find a small test-case
1102 # users, traceable to inspect.py. If I can find a small test-case
1110 # to reproduce this, I should either write a better workaround or
1103 # to reproduce this, I should either write a better workaround or
1111 # file a bug report against inspect (if that's the real problem).
1104 # file a bug report against inspect (if that's the real problem).
1112 # So far, I haven't been able to find an isolated example to
1105 # So far, I haven't been able to find an isolated example to
1113 # reproduce the problem.
1106 # reproduce the problem.
1114 inspect_error()
1107 inspect_error()
1115 traceback.print_exc(file=self.ostream)
1108 traceback.print_exc(file=self.ostream)
1116 info('\nUnfortunately, your original traceback can not be constructed.\n')
1109 info('\nUnfortunately, your original traceback can not be constructed.\n')
1117 return None
1110 return None
1118
1111
1119 def get_parts_of_chained_exception(self, evalue):
1112 def get_parts_of_chained_exception(self, evalue):
1120 def get_chained_exception(exception_value):
1113 def get_chained_exception(exception_value):
1121 cause = getattr(exception_value, '__cause__', None)
1114 cause = getattr(exception_value, '__cause__', None)
1122 if cause:
1115 if cause:
1123 return cause
1116 return cause
1124 if getattr(exception_value, '__suppress_context__', False):
1117 if getattr(exception_value, '__suppress_context__', False):
1125 return None
1118 return None
1126 return getattr(exception_value, '__context__', None)
1119 return getattr(exception_value, '__context__', None)
1127
1120
1128 chained_evalue = get_chained_exception(evalue)
1121 chained_evalue = get_chained_exception(evalue)
1129
1122
1130 if chained_evalue:
1123 if chained_evalue:
1131 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
1124 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
1132
1125
1133 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
1126 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
1134 number_of_lines_of_context=5):
1127 number_of_lines_of_context=5):
1135 """Return a nice text document describing the traceback."""
1128 """Return a nice text document describing the traceback."""
1136
1129
1137 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
1130 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
1138 tb_offset)
1131 tb_offset)
1139
1132
1140 colors = self.Colors # just a shorthand + quicker name lookup
1133 colors = self.Colors # just a shorthand + quicker name lookup
1141 colorsnormal = colors.Normal # used a lot
1134 colorsnormal = colors.Normal # used a lot
1142 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
1135 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
1143 structured_traceback_parts = [head]
1136 structured_traceback_parts = [head]
1144 if py3compat.PY3:
1137 if py3compat.PY3:
1145 chained_exceptions_tb_offset = 0
1138 chained_exceptions_tb_offset = 0
1146 lines_of_context = 3
1139 lines_of_context = 3
1147 formatted_exceptions = formatted_exception
1140 formatted_exceptions = formatted_exception
1148 exception = self.get_parts_of_chained_exception(evalue)
1141 exception = self.get_parts_of_chained_exception(evalue)
1149 if exception:
1142 if exception:
1150 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1143 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1151 etype, evalue, etb = exception
1144 etype, evalue, etb = exception
1152 else:
1145 else:
1153 evalue = None
1146 evalue = None
1154 chained_exc_ids = set()
1147 chained_exc_ids = set()
1155 while evalue:
1148 while evalue:
1156 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
1149 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
1157 chained_exceptions_tb_offset)
1150 chained_exceptions_tb_offset)
1158 exception = self.get_parts_of_chained_exception(evalue)
1151 exception = self.get_parts_of_chained_exception(evalue)
1159
1152
1160 if exception and not id(exception[1]) in chained_exc_ids:
1153 if exception and not id(exception[1]) in chained_exc_ids:
1161 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
1154 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
1162 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1155 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1163 etype, evalue, etb = exception
1156 etype, evalue, etb = exception
1164 else:
1157 else:
1165 evalue = None
1158 evalue = None
1166
1159
1167 # we want to see exceptions in a reversed order:
1160 # we want to see exceptions in a reversed order:
1168 # the first exception should be on top
1161 # the first exception should be on top
1169 for formatted_exception in reversed(formatted_exceptions):
1162 for formatted_exception in reversed(formatted_exceptions):
1170 structured_traceback_parts += formatted_exception
1163 structured_traceback_parts += formatted_exception
1171 else:
1164 else:
1172 structured_traceback_parts += formatted_exception[0]
1165 structured_traceback_parts += formatted_exception[0]
1173
1166
1174 return structured_traceback_parts
1167 return structured_traceback_parts
1175
1168
1176 def debugger(self, force=False):
1169 def debugger(self, force=False):
1177 """Call up the pdb debugger if desired, always clean up the tb
1170 """Call up the pdb debugger if desired, always clean up the tb
1178 reference.
1171 reference.
1179
1172
1180 Keywords:
1173 Keywords:
1181
1174
1182 - force(False): by default, this routine checks the instance call_pdb
1175 - force(False): by default, this routine checks the instance call_pdb
1183 flag and does not actually invoke the debugger if the flag is false.
1176 flag and does not actually invoke the debugger if the flag is false.
1184 The 'force' option forces the debugger to activate even if the flag
1177 The 'force' option forces the debugger to activate even if the flag
1185 is false.
1178 is false.
1186
1179
1187 If the call_pdb flag is set, the pdb interactive debugger is
1180 If the call_pdb flag is set, the pdb interactive debugger is
1188 invoked. In all cases, the self.tb reference to the current traceback
1181 invoked. In all cases, the self.tb reference to the current traceback
1189 is deleted to prevent lingering references which hamper memory
1182 is deleted to prevent lingering references which hamper memory
1190 management.
1183 management.
1191
1184
1192 Note that each call to pdb() does an 'import readline', so if your app
1185 Note that each call to pdb() does an 'import readline', so if your app
1193 requires a special setup for the readline completers, you'll have to
1186 requires a special setup for the readline completers, you'll have to
1194 fix that by hand after invoking the exception handler."""
1187 fix that by hand after invoking the exception handler."""
1195
1188
1196 if force or self.call_pdb:
1189 if force or self.call_pdb:
1197 if self.pdb is None:
1190 if self.pdb is None:
1198 self.pdb = self.debugger_cls()
1191 self.pdb = self.debugger_cls()
1199 # the system displayhook may have changed, restore the original
1192 # the system displayhook may have changed, restore the original
1200 # for pdb
1193 # for pdb
1201 display_trap = DisplayTrap(hook=sys.__displayhook__)
1194 display_trap = DisplayTrap(hook=sys.__displayhook__)
1202 with display_trap:
1195 with display_trap:
1203 self.pdb.reset()
1196 self.pdb.reset()
1204 # Find the right frame so we don't pop up inside ipython itself
1197 # Find the right frame so we don't pop up inside ipython itself
1205 if hasattr(self, 'tb') and self.tb is not None:
1198 if hasattr(self, 'tb') and self.tb is not None:
1206 etb = self.tb
1199 etb = self.tb
1207 else:
1200 else:
1208 etb = self.tb = sys.last_traceback
1201 etb = self.tb = sys.last_traceback
1209 while self.tb is not None and self.tb.tb_next is not None:
1202 while self.tb is not None and self.tb.tb_next is not None:
1210 self.tb = self.tb.tb_next
1203 self.tb = self.tb.tb_next
1211 if etb and etb.tb_next:
1204 if etb and etb.tb_next:
1212 etb = etb.tb_next
1205 etb = etb.tb_next
1213 self.pdb.botframe = etb.tb_frame
1206 self.pdb.botframe = etb.tb_frame
1214 self.pdb.interaction(self.tb.tb_frame, self.tb)
1207 self.pdb.interaction(self.tb.tb_frame, self.tb)
1215
1208
1216 if hasattr(self, 'tb'):
1209 if hasattr(self, 'tb'):
1217 del self.tb
1210 del self.tb
1218
1211
1219 def handler(self, info=None):
1212 def handler(self, info=None):
1220 (etype, evalue, etb) = info or sys.exc_info()
1213 (etype, evalue, etb) = info or sys.exc_info()
1221 self.tb = etb
1214 self.tb = etb
1222 ostream = self.ostream
1215 ostream = self.ostream
1223 ostream.flush()
1216 ostream.flush()
1224 ostream.write(self.text(etype, evalue, etb))
1217 ostream.write(self.text(etype, evalue, etb))
1225 ostream.write('\n')
1218 ostream.write('\n')
1226 ostream.flush()
1219 ostream.flush()
1227
1220
1228 # Changed so an instance can just be called as VerboseTB_inst() and print
1221 # Changed so an instance can just be called as VerboseTB_inst() and print
1229 # out the right info on its own.
1222 # out the right info on its own.
1230 def __call__(self, etype=None, evalue=None, etb=None):
1223 def __call__(self, etype=None, evalue=None, etb=None):
1231 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1224 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1232 if etb is None:
1225 if etb is None:
1233 self.handler()
1226 self.handler()
1234 else:
1227 else:
1235 self.handler((etype, evalue, etb))
1228 self.handler((etype, evalue, etb))
1236 try:
1229 try:
1237 self.debugger()
1230 self.debugger()
1238 except KeyboardInterrupt:
1231 except KeyboardInterrupt:
1239 print("\nKeyboardInterrupt")
1232 print("\nKeyboardInterrupt")
1240
1233
1241
1234
1242 #----------------------------------------------------------------------------
1235 #----------------------------------------------------------------------------
1243 class FormattedTB(VerboseTB, ListTB):
1236 class FormattedTB(VerboseTB, ListTB):
1244 """Subclass ListTB but allow calling with a traceback.
1237 """Subclass ListTB but allow calling with a traceback.
1245
1238
1246 It can thus be used as a sys.excepthook for Python > 2.1.
1239 It can thus be used as a sys.excepthook for Python > 2.1.
1247
1240
1248 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1241 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1249
1242
1250 Allows a tb_offset to be specified. This is useful for situations where
1243 Allows a tb_offset to be specified. This is useful for situations where
1251 one needs to remove a number of topmost frames from the traceback (such as
1244 one needs to remove a number of topmost frames from the traceback (such as
1252 occurs with python programs that themselves execute other python code,
1245 occurs with python programs that themselves execute other python code,
1253 like Python shells). """
1246 like Python shells). """
1254
1247
1255 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1248 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1256 ostream=None,
1249 ostream=None,
1257 tb_offset=0, long_header=False, include_vars=False,
1250 tb_offset=0, long_header=False, include_vars=False,
1258 check_cache=None, debugger_cls=None,
1251 check_cache=None, debugger_cls=None,
1259 parent=None, config=None):
1252 parent=None, config=None):
1260
1253
1261 # NEVER change the order of this list. Put new modes at the end:
1254 # NEVER change the order of this list. Put new modes at the end:
1262 self.valid_modes = ['Plain', 'Context', 'Verbose']
1255 self.valid_modes = ['Plain', 'Context', 'Verbose']
1263 self.verbose_modes = self.valid_modes[1:3]
1256 self.verbose_modes = self.valid_modes[1:3]
1264
1257
1265 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1258 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1266 ostream=ostream, tb_offset=tb_offset,
1259 ostream=ostream, tb_offset=tb_offset,
1267 long_header=long_header, include_vars=include_vars,
1260 long_header=long_header, include_vars=include_vars,
1268 check_cache=check_cache, debugger_cls=debugger_cls,
1261 check_cache=check_cache, debugger_cls=debugger_cls,
1269 parent=parent, config=config)
1262 parent=parent, config=config)
1270
1263
1271 # Different types of tracebacks are joined with different separators to
1264 # Different types of tracebacks are joined with different separators to
1272 # form a single string. They are taken from this dict
1265 # form a single string. They are taken from this dict
1273 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1266 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1274 # set_mode also sets the tb_join_char attribute
1267 # set_mode also sets the tb_join_char attribute
1275 self.set_mode(mode)
1268 self.set_mode(mode)
1276
1269
1277 def _extract_tb(self, tb):
1270 def _extract_tb(self, tb):
1278 if tb:
1271 if tb:
1279 return traceback.extract_tb(tb)
1272 return traceback.extract_tb(tb)
1280 else:
1273 else:
1281 return None
1274 return None
1282
1275
1283 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
1276 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
1284 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1277 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1285 mode = self.mode
1278 mode = self.mode
1286 if mode in self.verbose_modes:
1279 if mode in self.verbose_modes:
1287 # Verbose modes need a full traceback
1280 # Verbose modes need a full traceback
1288 return VerboseTB.structured_traceback(
1281 return VerboseTB.structured_traceback(
1289 self, etype, value, tb, tb_offset, number_of_lines_of_context
1282 self, etype, value, tb, tb_offset, number_of_lines_of_context
1290 )
1283 )
1291 else:
1284 else:
1292 # We must check the source cache because otherwise we can print
1285 # We must check the source cache because otherwise we can print
1293 # out-of-date source code.
1286 # out-of-date source code.
1294 self.check_cache()
1287 self.check_cache()
1295 # Now we can extract and format the exception
1288 # Now we can extract and format the exception
1296 elist = self._extract_tb(tb)
1289 elist = self._extract_tb(tb)
1297 return ListTB.structured_traceback(
1290 return ListTB.structured_traceback(
1298 self, etype, value, elist, tb_offset, number_of_lines_of_context
1291 self, etype, value, elist, tb_offset, number_of_lines_of_context
1299 )
1292 )
1300
1293
1301 def stb2text(self, stb):
1294 def stb2text(self, stb):
1302 """Convert a structured traceback (a list) to a string."""
1295 """Convert a structured traceback (a list) to a string."""
1303 return self.tb_join_char.join(stb)
1296 return self.tb_join_char.join(stb)
1304
1297
1305
1298
1306 def set_mode(self, mode=None):
1299 def set_mode(self, mode=None):
1307 """Switch to the desired mode.
1300 """Switch to the desired mode.
1308
1301
1309 If mode is not specified, cycles through the available modes."""
1302 If mode is not specified, cycles through the available modes."""
1310
1303
1311 if not mode:
1304 if not mode:
1312 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
1305 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
1313 len(self.valid_modes)
1306 len(self.valid_modes)
1314 self.mode = self.valid_modes[new_idx]
1307 self.mode = self.valid_modes[new_idx]
1315 elif mode not in self.valid_modes:
1308 elif mode not in self.valid_modes:
1316 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
1309 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
1317 'Valid modes: ' + str(self.valid_modes))
1310 'Valid modes: ' + str(self.valid_modes))
1318 else:
1311 else:
1319 self.mode = mode
1312 self.mode = mode
1320 # include variable details only in 'Verbose' mode
1313 # include variable details only in 'Verbose' mode
1321 self.include_vars = (self.mode == self.valid_modes[2])
1314 self.include_vars = (self.mode == self.valid_modes[2])
1322 # Set the join character for generating text tracebacks
1315 # Set the join character for generating text tracebacks
1323 self.tb_join_char = self._join_chars[self.mode]
1316 self.tb_join_char = self._join_chars[self.mode]
1324
1317
1325 # some convenient shortcuts
1318 # some convenient shortcuts
1326 def plain(self):
1319 def plain(self):
1327 self.set_mode(self.valid_modes[0])
1320 self.set_mode(self.valid_modes[0])
1328
1321
1329 def context(self):
1322 def context(self):
1330 self.set_mode(self.valid_modes[1])
1323 self.set_mode(self.valid_modes[1])
1331
1324
1332 def verbose(self):
1325 def verbose(self):
1333 self.set_mode(self.valid_modes[2])
1326 self.set_mode(self.valid_modes[2])
1334
1327
1335
1328
1336 #----------------------------------------------------------------------------
1329 #----------------------------------------------------------------------------
1337 class AutoFormattedTB(FormattedTB):
1330 class AutoFormattedTB(FormattedTB):
1338 """A traceback printer which can be called on the fly.
1331 """A traceback printer which can be called on the fly.
1339
1332
1340 It will find out about exceptions by itself.
1333 It will find out about exceptions by itself.
1341
1334
1342 A brief example::
1335 A brief example::
1343
1336
1344 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1337 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1345 try:
1338 try:
1346 ...
1339 ...
1347 except:
1340 except:
1348 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1341 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1349 """
1342 """
1350
1343
1351 def __call__(self, etype=None, evalue=None, etb=None,
1344 def __call__(self, etype=None, evalue=None, etb=None,
1352 out=None, tb_offset=None):
1345 out=None, tb_offset=None):
1353 """Print out a formatted exception traceback.
1346 """Print out a formatted exception traceback.
1354
1347
1355 Optional arguments:
1348 Optional arguments:
1356 - out: an open file-like object to direct output to.
1349 - out: an open file-like object to direct output to.
1357
1350
1358 - tb_offset: the number of frames to skip over in the stack, on a
1351 - tb_offset: the number of frames to skip over in the stack, on a
1359 per-call basis (this overrides temporarily the instance's tb_offset
1352 per-call basis (this overrides temporarily the instance's tb_offset
1360 given at initialization time. """
1353 given at initialization time. """
1361
1354
1362 if out is None:
1355 if out is None:
1363 out = self.ostream
1356 out = self.ostream
1364 out.flush()
1357 out.flush()
1365 out.write(self.text(etype, evalue, etb, tb_offset))
1358 out.write(self.text(etype, evalue, etb, tb_offset))
1366 out.write('\n')
1359 out.write('\n')
1367 out.flush()
1360 out.flush()
1368 # FIXME: we should remove the auto pdb behavior from here and leave
1361 # FIXME: we should remove the auto pdb behavior from here and leave
1369 # that to the clients.
1362 # that to the clients.
1370 try:
1363 try:
1371 self.debugger()
1364 self.debugger()
1372 except KeyboardInterrupt:
1365 except KeyboardInterrupt:
1373 print("\nKeyboardInterrupt")
1366 print("\nKeyboardInterrupt")
1374
1367
1375 def structured_traceback(self, etype=None, value=None, tb=None,
1368 def structured_traceback(self, etype=None, value=None, tb=None,
1376 tb_offset=None, number_of_lines_of_context=5):
1369 tb_offset=None, number_of_lines_of_context=5):
1377 if etype is None:
1370 if etype is None:
1378 etype, value, tb = sys.exc_info()
1371 etype, value, tb = sys.exc_info()
1379 self.tb = tb
1372 self.tb = tb
1380 return FormattedTB.structured_traceback(
1373 return FormattedTB.structured_traceback(
1381 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1374 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1382
1375
1383
1376
1384 #---------------------------------------------------------------------------
1377 #---------------------------------------------------------------------------
1385
1378
1386 # A simple class to preserve Nathan's original functionality.
1379 # A simple class to preserve Nathan's original functionality.
1387 class ColorTB(FormattedTB):
1380 class ColorTB(FormattedTB):
1388 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1381 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1389
1382
1390 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1383 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1391 FormattedTB.__init__(self, color_scheme=color_scheme,
1384 FormattedTB.__init__(self, color_scheme=color_scheme,
1392 call_pdb=call_pdb, **kwargs)
1385 call_pdb=call_pdb, **kwargs)
1393
1386
1394
1387
1395 class SyntaxTB(ListTB):
1388 class SyntaxTB(ListTB):
1396 """Extension which holds some state: the last exception value"""
1389 """Extension which holds some state: the last exception value"""
1397
1390
1398 def __init__(self, color_scheme='NoColor', parent=None, config=None):
1391 def __init__(self, color_scheme='NoColor', parent=None, config=None):
1399 ListTB.__init__(self, color_scheme, parent=parent, config=config)
1392 ListTB.__init__(self, color_scheme, parent=parent, config=config)
1400 self.last_syntax_error = None
1393 self.last_syntax_error = None
1401
1394
1402 def __call__(self, etype, value, elist):
1395 def __call__(self, etype, value, elist):
1403 self.last_syntax_error = value
1396 self.last_syntax_error = value
1404
1397
1405 ListTB.__call__(self, etype, value, elist)
1398 ListTB.__call__(self, etype, value, elist)
1406
1399
1407 def structured_traceback(self, etype, value, elist, tb_offset=None,
1400 def structured_traceback(self, etype, value, elist, tb_offset=None,
1408 context=5):
1401 context=5):
1409 # If the source file has been edited, the line in the syntax error can
1402 # If the source file has been edited, the line in the syntax error can
1410 # be wrong (retrieved from an outdated cache). This replaces it with
1403 # be wrong (retrieved from an outdated cache). This replaces it with
1411 # the current value.
1404 # the current value.
1412 if isinstance(value, SyntaxError) \
1405 if isinstance(value, SyntaxError) \
1413 and isinstance(value.filename, str) \
1406 and isinstance(value.filename, str) \
1414 and isinstance(value.lineno, int):
1407 and isinstance(value.lineno, int):
1415 linecache.checkcache(value.filename)
1408 linecache.checkcache(value.filename)
1416 newtext = ulinecache.getline(value.filename, value.lineno)
1409 newtext = ulinecache.getline(value.filename, value.lineno)
1417 if newtext:
1410 if newtext:
1418 value.text = newtext
1411 value.text = newtext
1419 self.last_syntax_error = value
1412 self.last_syntax_error = value
1420 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1413 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1421 tb_offset=tb_offset, context=context)
1414 tb_offset=tb_offset, context=context)
1422
1415
1423 def clear_err_state(self):
1416 def clear_err_state(self):
1424 """Return the current error state and clear it"""
1417 """Return the current error state and clear it"""
1425 e = self.last_syntax_error
1418 e = self.last_syntax_error
1426 self.last_syntax_error = None
1419 self.last_syntax_error = None
1427 return e
1420 return e
1428
1421
1429 def stb2text(self, stb):
1422 def stb2text(self, stb):
1430 """Convert a structured traceback (a list) to a string."""
1423 """Convert a structured traceback (a list) to a string."""
1431 return ''.join(stb)
1424 return ''.join(stb)
1432
1425
1433
1426
1434 # some internal-use functions
1427 # some internal-use functions
1435 def text_repr(value):
1428 def text_repr(value):
1436 """Hopefully pretty robust repr equivalent."""
1429 """Hopefully pretty robust repr equivalent."""
1437 # this is pretty horrible but should always return *something*
1430 # this is pretty horrible but should always return *something*
1438 try:
1431 try:
1439 return pydoc.text.repr(value)
1432 return pydoc.text.repr(value)
1440 except KeyboardInterrupt:
1433 except KeyboardInterrupt:
1441 raise
1434 raise
1442 except:
1435 except:
1443 try:
1436 try:
1444 return repr(value)
1437 return repr(value)
1445 except KeyboardInterrupt:
1438 except KeyboardInterrupt:
1446 raise
1439 raise
1447 except:
1440 except:
1448 try:
1441 try:
1449 # all still in an except block so we catch
1442 # all still in an except block so we catch
1450 # getattr raising
1443 # getattr raising
1451 name = getattr(value, '__name__', None)
1444 name = getattr(value, '__name__', None)
1452 if name:
1445 if name:
1453 # ick, recursion
1446 # ick, recursion
1454 return text_repr(name)
1447 return text_repr(name)
1455 klass = getattr(value, '__class__', None)
1448 klass = getattr(value, '__class__', None)
1456 if klass:
1449 if klass:
1457 return '%s instance' % text_repr(klass)
1450 return '%s instance' % text_repr(klass)
1458 except KeyboardInterrupt:
1451 except KeyboardInterrupt:
1459 raise
1452 raise
1460 except:
1453 except:
1461 return 'UNRECOVERABLE REPR FAILURE'
1454 return 'UNRECOVERABLE REPR FAILURE'
1462
1455
1463
1456
1464 def eqrepr(value, repr=text_repr):
1457 def eqrepr(value, repr=text_repr):
1465 return '=%s' % repr(value)
1458 return '=%s' % repr(value)
1466
1459
1467
1460
1468 def nullrepr(value, repr=text_repr):
1461 def nullrepr(value, repr=text_repr):
1469 return ''
1462 return ''
@@ -1,108 +1,106 b''
1 """prompt-toolkit utilities
1 """prompt-toolkit utilities
2
2
3 Everything in this module is a private API,
3 Everything in this module is a private API,
4 not to be used outside IPython.
4 not to be used outside IPython.
5 """
5 """
6
6
7 # Copyright (c) IPython Development Team.
7 # Copyright (c) IPython Development Team.
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9
9
10 import unicodedata
10 import unicodedata
11 from wcwidth import wcwidth
11 from wcwidth import wcwidth
12
12
13 from IPython.utils.py3compat import PY3
14
15 from IPython.core.completer import IPCompleter
13 from IPython.core.completer import IPCompleter
16 from prompt_toolkit.completion import Completer, Completion
14 from prompt_toolkit.completion import Completer, Completion
17 from prompt_toolkit.layout.lexers import Lexer
15 from prompt_toolkit.layout.lexers import Lexer
18 from prompt_toolkit.layout.lexers import PygmentsLexer
16 from prompt_toolkit.layout.lexers import PygmentsLexer
19
17
20 import pygments.lexers as pygments_lexers
18 import pygments.lexers as pygments_lexers
21
19
22
20
23 class IPythonPTCompleter(Completer):
21 class IPythonPTCompleter(Completer):
24 """Adaptor to provide IPython completions to prompt_toolkit"""
22 """Adaptor to provide IPython completions to prompt_toolkit"""
25 def __init__(self, ipy_completer=None, shell=None):
23 def __init__(self, ipy_completer=None, shell=None):
26 if shell is None and ipy_completer is None:
24 if shell is None and ipy_completer is None:
27 raise TypeError("Please pass shell=an InteractiveShell instance.")
25 raise TypeError("Please pass shell=an InteractiveShell instance.")
28 self._ipy_completer = ipy_completer
26 self._ipy_completer = ipy_completer
29 self.shell = shell
27 self.shell = shell
30
28
31 @property
29 @property
32 def ipy_completer(self):
30 def ipy_completer(self):
33 if self._ipy_completer:
31 if self._ipy_completer:
34 return self._ipy_completer
32 return self._ipy_completer
35 else:
33 else:
36 return self.shell.Completer
34 return self.shell.Completer
37
35
38 def get_completions(self, document, complete_event):
36 def get_completions(self, document, complete_event):
39 if not document.current_line.strip():
37 if not document.current_line.strip():
40 return
38 return
41
39
42 used, matches = self.ipy_completer.complete(
40 used, matches = self.ipy_completer.complete(
43 line_buffer=document.current_line,
41 line_buffer=document.current_line,
44 cursor_pos=document.cursor_position_col
42 cursor_pos=document.cursor_position_col
45 )
43 )
46 start_pos = -len(used)
44 start_pos = -len(used)
47 for m in matches:
45 for m in matches:
48 if not m:
46 if not m:
49 # Guard against completion machinery giving us an empty string.
47 # Guard against completion machinery giving us an empty string.
50 continue
48 continue
51
49
52 m = unicodedata.normalize('NFC', m)
50 m = unicodedata.normalize('NFC', m)
53
51
54 # When the first character of the completion has a zero length,
52 # When the first character of the completion has a zero length,
55 # then it's probably a decomposed unicode character. E.g. caused by
53 # then it's probably a decomposed unicode character. E.g. caused by
56 # the "\dot" completion. Try to compose again with the previous
54 # the "\dot" completion. Try to compose again with the previous
57 # character.
55 # character.
58 if wcwidth(m[0]) == 0:
56 if wcwidth(m[0]) == 0:
59 if document.cursor_position + start_pos > 0:
57 if document.cursor_position + start_pos > 0:
60 char_before = document.text[document.cursor_position + start_pos - 1]
58 char_before = document.text[document.cursor_position + start_pos - 1]
61 m = unicodedata.normalize('NFC', char_before + m)
59 m = unicodedata.normalize('NFC', char_before + m)
62
60
63 # Yield the modified completion instead, if this worked.
61 # Yield the modified completion instead, if this worked.
64 if wcwidth(m[0:1]) == 1:
62 if wcwidth(m[0:1]) == 1:
65 yield Completion(m, start_position=start_pos - 1)
63 yield Completion(m, start_position=start_pos - 1)
66 continue
64 continue
67
65
68 # TODO: Use Jedi to determine meta_text
66 # TODO: Use Jedi to determine meta_text
69 # (Jedi currently has a bug that results in incorrect information.)
67 # (Jedi currently has a bug that results in incorrect information.)
70 # meta_text = ''
68 # meta_text = ''
71 # yield Completion(m, start_position=start_pos,
69 # yield Completion(m, start_position=start_pos,
72 # display_meta=meta_text)
70 # display_meta=meta_text)
73 yield Completion(m, start_position=start_pos)
71 yield Completion(m, start_position=start_pos)
74
72
75 class IPythonPTLexer(Lexer):
73 class IPythonPTLexer(Lexer):
76 """
74 """
77 Wrapper around PythonLexer and BashLexer.
75 Wrapper around PythonLexer and BashLexer.
78 """
76 """
79 def __init__(self):
77 def __init__(self):
80 l = pygments_lexers
78 l = pygments_lexers
81 self.python_lexer = PygmentsLexer(l.Python3Lexer if PY3 else l.PythonLexer)
79 self.python_lexer = PygmentsLexer(l.Python3Lexer)
82 self.shell_lexer = PygmentsLexer(l.BashLexer)
80 self.shell_lexer = PygmentsLexer(l.BashLexer)
83
81
84 self.magic_lexers = {
82 self.magic_lexers = {
85 'HTML': PygmentsLexer(l.HtmlLexer),
83 'HTML': PygmentsLexer(l.HtmlLexer),
86 'html': PygmentsLexer(l.HtmlLexer),
84 'html': PygmentsLexer(l.HtmlLexer),
87 'javascript': PygmentsLexer(l.JavascriptLexer),
85 'javascript': PygmentsLexer(l.JavascriptLexer),
88 'js': PygmentsLexer(l.JavascriptLexer),
86 'js': PygmentsLexer(l.JavascriptLexer),
89 'perl': PygmentsLexer(l.PerlLexer),
87 'perl': PygmentsLexer(l.PerlLexer),
90 'ruby': PygmentsLexer(l.RubyLexer),
88 'ruby': PygmentsLexer(l.RubyLexer),
91 'latex': PygmentsLexer(l.TexLexer),
89 'latex': PygmentsLexer(l.TexLexer),
92 }
90 }
93
91
94 def lex_document(self, cli, document):
92 def lex_document(self, cli, document):
95 text = document.text.lstrip()
93 text = document.text.lstrip()
96
94
97 lexer = self.python_lexer
95 lexer = self.python_lexer
98
96
99 if text.startswith('!') or text.startswith('%%bash'):
97 if text.startswith('!') or text.startswith('%%bash'):
100 lexer = self.shell_lexer
98 lexer = self.shell_lexer
101
99
102 elif text.startswith('%%'):
100 elif text.startswith('%%'):
103 for magic, l in self.magic_lexers.items():
101 for magic, l in self.magic_lexers.items():
104 if text.startswith('%%' + magic):
102 if text.startswith('%%' + magic):
105 lexer = l
103 lexer = l
106 break
104 break
107
105
108 return lexer.lex_document(cli, document)
106 return lexer.lex_document(cli, document)
@@ -1,85 +1,81 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Tests for io.py"""
2 """Tests for io.py"""
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 io as stdlib_io
8 import io as stdlib_io
9 import os.path
9 import os.path
10 import stat
10 import stat
11 import sys
11 import sys
12 from io import StringIO
12
13
13 from subprocess import Popen, PIPE
14 from subprocess import Popen, PIPE
14 import unittest
15 import unittest
15
16
16 import nose.tools as nt
17 import nose.tools as nt
17
18
18 from IPython.testing.decorators import skipif, skip_win32
19 from IPython.testing.decorators import skipif, skip_win32
19 from IPython.utils.io import Tee, capture_output
20 from IPython.utils.io import Tee, capture_output
20 from IPython.utils.py3compat import doctest_refactor_print, PY3
21 from IPython.utils.py3compat import doctest_refactor_print
21 from IPython.utils.tempdir import TemporaryDirectory
22 from IPython.utils.tempdir import TemporaryDirectory
22
23
23 if PY3:
24 from io import StringIO
25 else:
26 from StringIO import StringIO
27
28
24
29 def test_tee_simple():
25 def test_tee_simple():
30 "Very simple check with stdout only"
26 "Very simple check with stdout only"
31 chan = StringIO()
27 chan = StringIO()
32 text = 'Hello'
28 text = 'Hello'
33 tee = Tee(chan, channel='stdout')
29 tee = Tee(chan, channel='stdout')
34 print(text, file=chan)
30 print(text, file=chan)
35 nt.assert_equal(chan.getvalue(), text+"\n")
31 nt.assert_equal(chan.getvalue(), text+"\n")
36
32
37
33
38 class TeeTestCase(unittest.TestCase):
34 class TeeTestCase(unittest.TestCase):
39
35
40 def tchan(self, channel, check='close'):
36 def tchan(self, channel, check='close'):
41 trap = StringIO()
37 trap = StringIO()
42 chan = StringIO()
38 chan = StringIO()
43 text = 'Hello'
39 text = 'Hello'
44
40
45 std_ori = getattr(sys, channel)
41 std_ori = getattr(sys, channel)
46 setattr(sys, channel, trap)
42 setattr(sys, channel, trap)
47
43
48 tee = Tee(chan, channel=channel)
44 tee = Tee(chan, channel=channel)
49 print(text, end='', file=chan)
45 print(text, end='', file=chan)
50 setattr(sys, channel, std_ori)
46 setattr(sys, channel, std_ori)
51 trap_val = trap.getvalue()
47 trap_val = trap.getvalue()
52 nt.assert_equal(chan.getvalue(), text)
48 nt.assert_equal(chan.getvalue(), text)
53 if check=='close':
49 if check=='close':
54 tee.close()
50 tee.close()
55 else:
51 else:
56 del tee
52 del tee
57
53
58 def test(self):
54 def test(self):
59 for chan in ['stdout', 'stderr']:
55 for chan in ['stdout', 'stderr']:
60 for check in ['close', 'del']:
56 for check in ['close', 'del']:
61 self.tchan(chan, check)
57 self.tchan(chan, check)
62
58
63 def test_io_init():
59 def test_io_init():
64 """Test that io.stdin/out/err exist at startup"""
60 """Test that io.stdin/out/err exist at startup"""
65 for name in ('stdin', 'stdout', 'stderr'):
61 for name in ('stdin', 'stdout', 'stderr'):
66 cmd = doctest_refactor_print("from IPython.utils import io;print io.%s.__class__"%name)
62 cmd = doctest_refactor_print("from IPython.utils import io;print io.%s.__class__"%name)
67 p = Popen([sys.executable, '-c', cmd],
63 p = Popen([sys.executable, '-c', cmd],
68 stdout=PIPE)
64 stdout=PIPE)
69 p.wait()
65 p.wait()
70 classname = p.stdout.read().strip().decode('ascii')
66 classname = p.stdout.read().strip().decode('ascii')
71 # __class__ is a reference to the class object in Python 3, so we can't
67 # __class__ is a reference to the class object in Python 3, so we can't
72 # just test for string equality.
68 # just test for string equality.
73 assert 'IPython.utils.io.IOStream' in classname, classname
69 assert 'IPython.utils.io.IOStream' in classname, classname
74
70
75 def test_capture_output():
71 def test_capture_output():
76 """capture_output() context works"""
72 """capture_output() context works"""
77
73
78 with capture_output() as io:
74 with capture_output() as io:
79 print('hi, stdout')
75 print('hi, stdout')
80 print('hi, stderr', file=sys.stderr)
76 print('hi, stderr', file=sys.stderr)
81
77
82 nt.assert_equal(io.stdout, 'hi, stdout\n')
78 nt.assert_equal(io.stdout, 'hi, stdout\n')
83 nt.assert_equal(io.stderr, 'hi, stderr\n')
79 nt.assert_equal(io.stderr, 'hi, stderr\n')
84
80
85
81
General Comments 0
You need to be logged in to leave comments. Login now