##// END OF EJS Templates
Improve error tracebacks so that it shows the cell prompts
martinRenou -
Show More
@@ -0,0 +1,39 b''
1 Traceback improvements
2 ======================
3
4 Previously, error tracebacks for errors happening in code cells were showing a hash, the one used for compiling the Python AST.
5
6 In [1]: def foo():
7 ...: return 3 / 0
8 ...:
9
10 In [2]: foo()
11 ---------------------------------------------------------------------------
12 ZeroDivisionError Traceback (most recent call last)
13 <ipython-input-2-c19b6d9633cf> in <module>
14 ----> 1 foo()
15
16 <ipython-input-1-1595a74c32d5> in foo()
17 1 def foo():
18 ----> 2 return 3 / 0
19 3
20
21 ZeroDivisionError: division by zero
22
23 The error traceback is now correctly formatted, showing the cell number in which the error happened:
24
25 In [1]: def foo():
26 ...: return 3 / 0
27 ...:
28
29 In [2]: foo()
30 ---------------------------------------------------------------------------
31 ZeroDivisionError Traceback (most recent call last)
32 In [2], in <module>
33 ----> 1 foo()
34
35 In [1], in foo()
36 1 def foo():
37 ----> 2 return 3 / 0
38
39 ZeroDivisionError: division by zero
@@ -1,188 +1,196 b''
1 """Compiler tools with improved interactive support.
1 """Compiler tools with improved interactive support.
2
2
3 Provides compilation machinery similar to codeop, but with caching support so
3 Provides compilation machinery similar to codeop, but with caching support so
4 we can provide interactive tracebacks.
4 we can provide interactive tracebacks.
5
5
6 Authors
6 Authors
7 -------
7 -------
8 * Robert Kern
8 * Robert Kern
9 * Fernando Perez
9 * Fernando Perez
10 * Thomas Kluyver
10 * Thomas Kluyver
11 """
11 """
12
12
13 # Note: though it might be more natural to name this module 'compiler', that
13 # Note: though it might be more natural to name this module 'compiler', that
14 # name is in the stdlib and name collisions with the stdlib tend to produce
14 # name is in the stdlib and name collisions with the stdlib tend to produce
15 # weird problems (often with third-party tools).
15 # weird problems (often with third-party tools).
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Copyright (C) 2010-2011 The IPython Development Team.
18 # Copyright (C) 2010-2011 The IPython Development Team.
19 #
19 #
20 # Distributed under the terms of the BSD License.
20 # Distributed under the terms of the BSD License.
21 #
21 #
22 # The full license is in the file COPYING.txt, distributed with this software.
22 # The full license is in the file COPYING.txt, distributed with this software.
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26 # Imports
26 # Imports
27 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
28
28
29 # Stdlib imports
29 # Stdlib imports
30 import __future__
30 import __future__
31 from ast import PyCF_ONLY_AST
31 from ast import PyCF_ONLY_AST
32 import codeop
32 import codeop
33 import functools
33 import functools
34 import hashlib
34 import hashlib
35 import linecache
35 import linecache
36 import operator
36 import operator
37 import time
37 import time
38 from contextlib import contextmanager
38 from contextlib import contextmanager
39
39
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41 # Constants
41 # Constants
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43
43
44 # Roughly equal to PyCF_MASK | PyCF_MASK_OBSOLETE as defined in pythonrun.h,
44 # Roughly equal to PyCF_MASK | PyCF_MASK_OBSOLETE as defined in pythonrun.h,
45 # this is used as a bitmask to extract future-related code flags.
45 # this is used as a bitmask to extract future-related code flags.
46 PyCF_MASK = functools.reduce(operator.or_,
46 PyCF_MASK = functools.reduce(operator.or_,
47 (getattr(__future__, fname).compiler_flag
47 (getattr(__future__, fname).compiler_flag
48 for fname in __future__.all_feature_names))
48 for fname in __future__.all_feature_names))
49
49
50 #-----------------------------------------------------------------------------
50 #-----------------------------------------------------------------------------
51 # Local utilities
51 # Local utilities
52 #-----------------------------------------------------------------------------
52 #-----------------------------------------------------------------------------
53
53
54 def code_name(code, number=0):
54 def code_name(code, number=0):
55 """ Compute a (probably) unique name for code for caching.
55 """ Compute a (probably) unique name for code for caching.
56
56
57 This now expects code to be unicode.
57 This now expects code to be unicode.
58 """
58 """
59 hash_digest = hashlib.sha1(code.encode("utf-8")).hexdigest()
59 hash_digest = hashlib.sha1(code.encode("utf-8")).hexdigest()
60 # Include the number and 12 characters of the hash in the name. It's
60 # Include the number and 12 characters of the hash in the name. It's
61 # pretty much impossible that in a single session we'll have collisions
61 # pretty much impossible that in a single session we'll have collisions
62 # even with truncated hashes, and the full one makes tracebacks too long
62 # even with truncated hashes, and the full one makes tracebacks too long
63 return '<ipython-input-{0}-{1}>'.format(number, hash_digest[:12])
63 return '<ipython-input-{0}-{1}>'.format(number, hash_digest[:12])
64
64
65 #-----------------------------------------------------------------------------
65 #-----------------------------------------------------------------------------
66 # Classes and functions
66 # Classes and functions
67 #-----------------------------------------------------------------------------
67 #-----------------------------------------------------------------------------
68
68
69 class CachingCompiler(codeop.Compile):
69 class CachingCompiler(codeop.Compile):
70 """A compiler that caches code compiled from interactive statements.
70 """A compiler that caches code compiled from interactive statements.
71 """
71 """
72
72
73 def __init__(self):
73 def __init__(self):
74 codeop.Compile.__init__(self)
74 codeop.Compile.__init__(self)
75
75
76 # This is ugly, but it must be done this way to allow multiple
76 # This is ugly, but it must be done this way to allow multiple
77 # simultaneous ipython instances to coexist. Since Python itself
77 # simultaneous ipython instances to coexist. Since Python itself
78 # directly accesses the data structures in the linecache module, and
78 # directly accesses the data structures in the linecache module, and
79 # the cache therein is global, we must work with that data structure.
79 # the cache therein is global, we must work with that data structure.
80 # We must hold a reference to the original checkcache routine and call
80 # We must hold a reference to the original checkcache routine and call
81 # that in our own check_cache() below, but the special IPython cache
81 # that in our own check_cache() below, but the special IPython cache
82 # must also be shared by all IPython instances. If we were to hold
82 # must also be shared by all IPython instances. If we were to hold
83 # separate caches (one in each CachingCompiler instance), any call made
83 # separate caches (one in each CachingCompiler instance), any call made
84 # by Python itself to linecache.checkcache() would obliterate the
84 # by Python itself to linecache.checkcache() would obliterate the
85 # cached data from the other IPython instances.
85 # cached data from the other IPython instances.
86 if not hasattr(linecache, '_ipython_cache'):
86 if not hasattr(linecache, '_ipython_cache'):
87 linecache._ipython_cache = {}
87 linecache._ipython_cache = {}
88 if not hasattr(linecache, '_checkcache_ori'):
88 if not hasattr(linecache, '_checkcache_ori'):
89 linecache._checkcache_ori = linecache.checkcache
89 linecache._checkcache_ori = linecache.checkcache
90 # Now, we must monkeypatch the linecache directly so that parts of the
90 # Now, we must monkeypatch the linecache directly so that parts of the
91 # stdlib that call it outside our control go through our codepath
91 # stdlib that call it outside our control go through our codepath
92 # (otherwise we'd lose our tracebacks).
92 # (otherwise we'd lose our tracebacks).
93 linecache.checkcache = check_linecache_ipython
93 linecache.checkcache = check_linecache_ipython
94
94
95 # Caching a dictionary { filename: execution_count } for nicely
96 # rendered tracebacks. The filename corresponds to the filename
97 # argument used for the builtins.compile function.
98 self._filename_map = {}
95
99
96 def ast_parse(self, source, filename='<unknown>', symbol='exec'):
100 def ast_parse(self, source, filename='<unknown>', symbol='exec'):
97 """Parse code to an AST with the current compiler flags active.
101 """Parse code to an AST with the current compiler flags active.
98
102
99 Arguments are exactly the same as ast.parse (in the standard library),
103 Arguments are exactly the same as ast.parse (in the standard library),
100 and are passed to the built-in compile function."""
104 and are passed to the built-in compile function."""
101 return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1)
105 return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1)
102
106
103 def reset_compiler_flags(self):
107 def reset_compiler_flags(self):
104 """Reset compiler flags to default state."""
108 """Reset compiler flags to default state."""
105 # This value is copied from codeop.Compile.__init__, so if that ever
109 # This value is copied from codeop.Compile.__init__, so if that ever
106 # changes, it will need to be updated.
110 # changes, it will need to be updated.
107 self.flags = codeop.PyCF_DONT_IMPLY_DEDENT
111 self.flags = codeop.PyCF_DONT_IMPLY_DEDENT
108
112
109 @property
113 @property
110 def compiler_flags(self):
114 def compiler_flags(self):
111 """Flags currently active in the compilation process.
115 """Flags currently active in the compilation process.
112 """
116 """
113 return self.flags
117 return self.flags
114
118
115 def get_code_name(self, raw_code, transformed_code, number):
119 def get_code_name(self, raw_code, transformed_code, number):
116 """Compute filename given the code, and the cell number.
120 """Compute filename given the code, and the cell number.
117
121
118 Parameters
122 Parameters
119 ----------
123 ----------
120 raw_code : str
124 raw_code : str
121 The raw cell code.
125 The raw cell code.
122 transformed_code : str
126 transformed_code : str
123 The executable Python source code to cache and compile.
127 The executable Python source code to cache and compile.
124 number : int
128 number : int
125 A number which forms part of the code's name. Used for the execution
129 A number which forms part of the code's name. Used for the execution
126 counter.
130 counter.
127
131
128 Returns
132 Returns
129 -------
133 -------
130 The computed filename.
134 The computed filename.
131 """
135 """
132 return code_name(transformed_code, number)
136 return code_name(transformed_code, number)
133
137
134 def cache(self, transformed_code, number=0, raw_code=None):
138 def cache(self, transformed_code, number=0, raw_code=None):
135 """Make a name for a block of code, and cache the code.
139 """Make a name for a block of code, and cache the code.
136
140
137 Parameters
141 Parameters
138 ----------
142 ----------
139 transformed_code : str
143 transformed_code : str
140 The executable Python source code to cache and compile.
144 The executable Python source code to cache and compile.
141 number : int
145 number : int
142 A number which forms part of the code's name. Used for the execution
146 A number which forms part of the code's name. Used for the execution
143 counter.
147 counter.
144 raw_code : str
148 raw_code : str
145 The raw code before transformation, if None, set to `transformed_code`.
149 The raw code before transformation, if None, set to `transformed_code`.
146
150
147 Returns
151 Returns
148 -------
152 -------
149 The name of the cached code (as a string). Pass this as the filename
153 The name of the cached code (as a string). Pass this as the filename
150 argument to compilation, so that tracebacks are correctly hooked up.
154 argument to compilation, so that tracebacks are correctly hooked up.
151 """
155 """
152 if raw_code is None:
156 if raw_code is None:
153 raw_code = transformed_code
157 raw_code = transformed_code
154
158
155 name = self.get_code_name(raw_code, transformed_code, number)
159 name = self.get_code_name(raw_code, transformed_code, number)
160
161 # Save the execution count
162 self._filename_map[name] = number
163
156 entry = (
164 entry = (
157 len(transformed_code),
165 len(transformed_code),
158 time.time(),
166 time.time(),
159 [line + "\n" for line in transformed_code.splitlines()],
167 [line + "\n" for line in transformed_code.splitlines()],
160 name,
168 name,
161 )
169 )
162 linecache.cache[name] = entry
170 linecache.cache[name] = entry
163 linecache._ipython_cache[name] = entry
171 linecache._ipython_cache[name] = entry
164 return name
172 return name
165
173
166 @contextmanager
174 @contextmanager
167 def extra_flags(self, flags):
175 def extra_flags(self, flags):
168 ## bits that we'll set to 1
176 ## bits that we'll set to 1
169 turn_on_bits = ~self.flags & flags
177 turn_on_bits = ~self.flags & flags
170
178
171
179
172 self.flags = self.flags | flags
180 self.flags = self.flags | flags
173 try:
181 try:
174 yield
182 yield
175 finally:
183 finally:
176 # turn off only the bits we turned on so that something like
184 # turn off only the bits we turned on so that something like
177 # __future__ that set flags stays.
185 # __future__ that set flags stays.
178 self.flags &= ~turn_on_bits
186 self.flags &= ~turn_on_bits
179
187
180
188
181 def check_linecache_ipython(*args):
189 def check_linecache_ipython(*args):
182 """Call linecache.checkcache() safely protecting our cached values.
190 """Call linecache.checkcache() safely protecting our cached values.
183 """
191 """
184 # First call the original checkcache as intended
192 # First call the original checkcache as intended
185 linecache._checkcache_ori(*args)
193 linecache._checkcache_ori(*args)
186 # Then, update back the cache with our data, so that tracebacks related
194 # Then, update back the cache with our data, so that tracebacks related
187 # to our compiled codes can be produced.
195 # to our compiled codes can be produced.
188 linecache.cache.update(linecache._ipython_cache)
196 linecache.cache.update(linecache._ipython_cache)
@@ -1,1087 +1,1093 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 unencrypted
44 potentially leak sensitive information like access keys, or unencrypted
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 inspect
92 import inspect
93 import linecache
93 import linecache
94 import pydoc
94 import pydoc
95 import sys
95 import sys
96 import time
96 import time
97 import traceback
97 import traceback
98
98
99 import stack_data
99 import stack_data
100 from pygments.formatters.terminal256 import Terminal256Formatter
100 from pygments.formatters.terminal256 import Terminal256Formatter
101 from pygments.styles import get_style_by_name
101 from pygments.styles import get_style_by_name
102
102
103 # IPython's own modules
103 # IPython's own modules
104 from IPython import get_ipython
104 from IPython import get_ipython
105 from IPython.core import debugger
105 from IPython.core import debugger
106 from IPython.core.display_trap import DisplayTrap
106 from IPython.core.display_trap import DisplayTrap
107 from IPython.core.excolors import exception_colors
107 from IPython.core.excolors import exception_colors
108 from IPython.utils import path as util_path
108 from IPython.utils import path as util_path
109 from IPython.utils import py3compat
109 from IPython.utils import py3compat
110 from IPython.utils.terminal import get_terminal_size
110 from IPython.utils.terminal import get_terminal_size
111
111
112 import IPython.utils.colorable as colorable
112 import IPython.utils.colorable as colorable
113
113
114 # Globals
114 # Globals
115 # amount of space to put line numbers before verbose tracebacks
115 # amount of space to put line numbers before verbose tracebacks
116 INDENT_SIZE = 8
116 INDENT_SIZE = 8
117
117
118 # Default color scheme. This is used, for example, by the traceback
118 # Default color scheme. This is used, for example, by the traceback
119 # formatter. When running in an actual IPython instance, the user's rc.colors
119 # formatter. When running in an actual IPython instance, the user's rc.colors
120 # value is used, but having a module global makes this functionality available
120 # value is used, but having a module global makes this functionality available
121 # to users of ultratb who are NOT running inside ipython.
121 # to users of ultratb who are NOT running inside ipython.
122 DEFAULT_SCHEME = 'NoColor'
122 DEFAULT_SCHEME = 'NoColor'
123
123
124 # ---------------------------------------------------------------------------
124 # ---------------------------------------------------------------------------
125 # Code begins
125 # Code begins
126
126
127 # Helper function -- largely belongs to VerboseTB, but we need the same
127 # Helper function -- largely belongs to VerboseTB, but we need the same
128 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
128 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
129 # can be recognized properly by ipython.el's py-traceback-line-re
129 # can be recognized properly by ipython.el's py-traceback-line-re
130 # (SyntaxErrors have to be treated specially because they have no traceback)
130 # (SyntaxErrors have to be treated specially because they have no traceback)
131
131
132
132
133 def _format_traceback_lines(lines, Colors, has_colors, lvals):
133 def _format_traceback_lines(lines, Colors, has_colors, lvals):
134 """
134 """
135 Format tracebacks lines with pointing arrow, leading numbers...
135 Format tracebacks lines with pointing arrow, leading numbers...
136
136
137 Parameters
137 Parameters
138 ----------
138 ----------
139 lines : list[Line]
139 lines : list[Line]
140 Colors
140 Colors
141 ColorScheme used.
141 ColorScheme used.
142 lvals : str
142 lvals : str
143 Values of local variables, already colored, to inject just after the error line.
143 Values of local variables, already colored, to inject just after the error line.
144 """
144 """
145 numbers_width = INDENT_SIZE - 1
145 numbers_width = INDENT_SIZE - 1
146 res = []
146 res = []
147
147
148 for stack_line in lines:
148 for stack_line in lines:
149 if stack_line is stack_data.LINE_GAP:
149 if stack_line is stack_data.LINE_GAP:
150 res.append('%s (...)%s\n' % (Colors.linenoEm, Colors.Normal))
150 res.append('%s (...)%s\n' % (Colors.linenoEm, Colors.Normal))
151 continue
151 continue
152
152
153 line = stack_line.render(pygmented=has_colors).rstrip('\n') + '\n'
153 line = stack_line.render(pygmented=has_colors).rstrip('\n') + '\n'
154 lineno = stack_line.lineno
154 lineno = stack_line.lineno
155 if stack_line.is_current:
155 if stack_line.is_current:
156 # This is the line with the error
156 # This is the line with the error
157 pad = numbers_width - len(str(lineno))
157 pad = numbers_width - len(str(lineno))
158 num = '%s%s' % (debugger.make_arrow(pad), str(lineno))
158 num = '%s%s' % (debugger.make_arrow(pad), str(lineno))
159 start_color = Colors.linenoEm
159 start_color = Colors.linenoEm
160 else:
160 else:
161 num = '%*s' % (numbers_width, lineno)
161 num = '%*s' % (numbers_width, lineno)
162 start_color = Colors.lineno
162 start_color = Colors.lineno
163
163
164 line = '%s%s%s %s' % (start_color, num, Colors.Normal, line)
164 line = '%s%s%s %s' % (start_color, num, Colors.Normal, line)
165
165
166 res.append(line)
166 res.append(line)
167 if lvals and stack_line.is_current:
167 if lvals and stack_line.is_current:
168 res.append(lvals + '\n')
168 res.append(lvals + '\n')
169 return res
169 return res
170
170
171
171
172 #---------------------------------------------------------------------------
172 #---------------------------------------------------------------------------
173 # Module classes
173 # Module classes
174 class TBTools(colorable.Colorable):
174 class TBTools(colorable.Colorable):
175 """Basic tools used by all traceback printer classes."""
175 """Basic tools used by all traceback printer classes."""
176
176
177 # Number of frames to skip when reporting tracebacks
177 # Number of frames to skip when reporting tracebacks
178 tb_offset = 0
178 tb_offset = 0
179
179
180 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
180 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
181 # Whether to call the interactive pdb debugger after printing
181 # Whether to call the interactive pdb debugger after printing
182 # tracebacks or not
182 # tracebacks or not
183 super(TBTools, self).__init__(parent=parent, config=config)
183 super(TBTools, self).__init__(parent=parent, config=config)
184 self.call_pdb = call_pdb
184 self.call_pdb = call_pdb
185
185
186 # Output stream to write to. Note that we store the original value in
186 # Output stream to write to. Note that we store the original value in
187 # a private attribute and then make the public ostream a property, so
187 # a private attribute and then make the public ostream a property, so
188 # that we can delay accessing sys.stdout until runtime. The way
188 # that we can delay accessing sys.stdout until runtime. The way
189 # things are written now, the sys.stdout object is dynamically managed
189 # things are written now, the sys.stdout object is dynamically managed
190 # so a reference to it should NEVER be stored statically. This
190 # so a reference to it should NEVER be stored statically. This
191 # property approach confines this detail to a single location, and all
191 # property approach confines this detail to a single location, and all
192 # subclasses can simply access self.ostream for writing.
192 # subclasses can simply access self.ostream for writing.
193 self._ostream = ostream
193 self._ostream = ostream
194
194
195 # Create color table
195 # Create color table
196 self.color_scheme_table = exception_colors()
196 self.color_scheme_table = exception_colors()
197
197
198 self.set_colors(color_scheme)
198 self.set_colors(color_scheme)
199 self.old_scheme = color_scheme # save initial value for toggles
199 self.old_scheme = color_scheme # save initial value for toggles
200
200
201 if call_pdb:
201 if call_pdb:
202 self.pdb = debugger.Pdb()
202 self.pdb = debugger.Pdb()
203 else:
203 else:
204 self.pdb = None
204 self.pdb = None
205
205
206 def _get_ostream(self):
206 def _get_ostream(self):
207 """Output stream that exceptions are written to.
207 """Output stream that exceptions are written to.
208
208
209 Valid values are:
209 Valid values are:
210
210
211 - None: the default, which means that IPython will dynamically resolve
211 - None: the default, which means that IPython will dynamically resolve
212 to sys.stdout. This ensures compatibility with most tools, including
212 to sys.stdout. This ensures compatibility with most tools, including
213 Windows (where plain stdout doesn't recognize ANSI escapes).
213 Windows (where plain stdout doesn't recognize ANSI escapes).
214
214
215 - Any object with 'write' and 'flush' attributes.
215 - Any object with 'write' and 'flush' attributes.
216 """
216 """
217 return sys.stdout if self._ostream is None else self._ostream
217 return sys.stdout if self._ostream is None else self._ostream
218
218
219 def _set_ostream(self, val):
219 def _set_ostream(self, val):
220 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
220 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
221 self._ostream = val
221 self._ostream = val
222
222
223 ostream = property(_get_ostream, _set_ostream)
223 ostream = property(_get_ostream, _set_ostream)
224
224
225 def get_parts_of_chained_exception(self, evalue):
225 def get_parts_of_chained_exception(self, evalue):
226 def get_chained_exception(exception_value):
226 def get_chained_exception(exception_value):
227 cause = getattr(exception_value, '__cause__', None)
227 cause = getattr(exception_value, '__cause__', None)
228 if cause:
228 if cause:
229 return cause
229 return cause
230 if getattr(exception_value, '__suppress_context__', False):
230 if getattr(exception_value, '__suppress_context__', False):
231 return None
231 return None
232 return getattr(exception_value, '__context__', None)
232 return getattr(exception_value, '__context__', None)
233
233
234 chained_evalue = get_chained_exception(evalue)
234 chained_evalue = get_chained_exception(evalue)
235
235
236 if chained_evalue:
236 if chained_evalue:
237 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
237 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
238
238
239 def prepare_chained_exception_message(self, cause):
239 def prepare_chained_exception_message(self, cause):
240 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
240 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
241 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
241 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
242
242
243 if cause:
243 if cause:
244 message = [[direct_cause]]
244 message = [[direct_cause]]
245 else:
245 else:
246 message = [[exception_during_handling]]
246 message = [[exception_during_handling]]
247 return message
247 return message
248
248
249 @property
249 @property
250 def has_colors(self):
250 def has_colors(self):
251 return self.color_scheme_table.active_scheme_name.lower() != "nocolor"
251 return self.color_scheme_table.active_scheme_name.lower() != "nocolor"
252
252
253 def set_colors(self, *args, **kw):
253 def set_colors(self, *args, **kw):
254 """Shorthand access to the color table scheme selector method."""
254 """Shorthand access to the color table scheme selector method."""
255
255
256 # Set own color table
256 # Set own color table
257 self.color_scheme_table.set_active_scheme(*args, **kw)
257 self.color_scheme_table.set_active_scheme(*args, **kw)
258 # for convenience, set Colors to the active scheme
258 # for convenience, set Colors to the active scheme
259 self.Colors = self.color_scheme_table.active_colors
259 self.Colors = self.color_scheme_table.active_colors
260 # Also set colors of debugger
260 # Also set colors of debugger
261 if hasattr(self, 'pdb') and self.pdb is not None:
261 if hasattr(self, 'pdb') and self.pdb is not None:
262 self.pdb.set_colors(*args, **kw)
262 self.pdb.set_colors(*args, **kw)
263
263
264 def color_toggle(self):
264 def color_toggle(self):
265 """Toggle between the currently active color scheme and NoColor."""
265 """Toggle between the currently active color scheme and NoColor."""
266
266
267 if self.color_scheme_table.active_scheme_name == 'NoColor':
267 if self.color_scheme_table.active_scheme_name == 'NoColor':
268 self.color_scheme_table.set_active_scheme(self.old_scheme)
268 self.color_scheme_table.set_active_scheme(self.old_scheme)
269 self.Colors = self.color_scheme_table.active_colors
269 self.Colors = self.color_scheme_table.active_colors
270 else:
270 else:
271 self.old_scheme = self.color_scheme_table.active_scheme_name
271 self.old_scheme = self.color_scheme_table.active_scheme_name
272 self.color_scheme_table.set_active_scheme('NoColor')
272 self.color_scheme_table.set_active_scheme('NoColor')
273 self.Colors = self.color_scheme_table.active_colors
273 self.Colors = self.color_scheme_table.active_colors
274
274
275 def stb2text(self, stb):
275 def stb2text(self, stb):
276 """Convert a structured traceback (a list) to a string."""
276 """Convert a structured traceback (a list) to a string."""
277 return '\n'.join(stb)
277 return '\n'.join(stb)
278
278
279 def text(self, etype, value, tb, tb_offset=None, context=5):
279 def text(self, etype, value, tb, tb_offset=None, context=5):
280 """Return formatted traceback.
280 """Return formatted traceback.
281
281
282 Subclasses may override this if they add extra arguments.
282 Subclasses may override this if they add extra arguments.
283 """
283 """
284 tb_list = self.structured_traceback(etype, value, tb,
284 tb_list = self.structured_traceback(etype, value, tb,
285 tb_offset, context)
285 tb_offset, context)
286 return self.stb2text(tb_list)
286 return self.stb2text(tb_list)
287
287
288 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
288 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
289 context=5, mode=None):
289 context=5, mode=None):
290 """Return a list of traceback frames.
290 """Return a list of traceback frames.
291
291
292 Must be implemented by each class.
292 Must be implemented by each class.
293 """
293 """
294 raise NotImplementedError()
294 raise NotImplementedError()
295
295
296
296
297 #---------------------------------------------------------------------------
297 #---------------------------------------------------------------------------
298 class ListTB(TBTools):
298 class ListTB(TBTools):
299 """Print traceback information from a traceback list, with optional color.
299 """Print traceback information from a traceback list, with optional color.
300
300
301 Calling requires 3 arguments: (etype, evalue, elist)
301 Calling requires 3 arguments: (etype, evalue, elist)
302 as would be obtained by::
302 as would be obtained by::
303
303
304 etype, evalue, tb = sys.exc_info()
304 etype, evalue, tb = sys.exc_info()
305 if tb:
305 if tb:
306 elist = traceback.extract_tb(tb)
306 elist = traceback.extract_tb(tb)
307 else:
307 else:
308 elist = None
308 elist = None
309
309
310 It can thus be used by programs which need to process the traceback before
310 It can thus be used by programs which need to process the traceback before
311 printing (such as console replacements based on the code module from the
311 printing (such as console replacements based on the code module from the
312 standard library).
312 standard library).
313
313
314 Because they are meant to be called without a full traceback (only a
314 Because they are meant to be called without a full traceback (only a
315 list), instances of this class can't call the interactive pdb debugger."""
315 list), instances of this class can't call the interactive pdb debugger."""
316
316
317 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
317 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
318 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
318 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
319 ostream=ostream, parent=parent,config=config)
319 ostream=ostream, parent=parent,config=config)
320
320
321 def __call__(self, etype, value, elist):
321 def __call__(self, etype, value, elist):
322 self.ostream.flush()
322 self.ostream.flush()
323 self.ostream.write(self.text(etype, value, elist))
323 self.ostream.write(self.text(etype, value, elist))
324 self.ostream.write('\n')
324 self.ostream.write('\n')
325
325
326 def _extract_tb(self, tb):
326 def _extract_tb(self, tb):
327 if tb:
327 if tb:
328 return traceback.extract_tb(tb)
328 return traceback.extract_tb(tb)
329 else:
329 else:
330 return None
330 return None
331
331
332 def structured_traceback(self, etype, evalue, etb=None, tb_offset=None,
332 def structured_traceback(self, etype, evalue, etb=None, tb_offset=None,
333 context=5):
333 context=5):
334 """Return a color formatted string with the traceback info.
334 """Return a color formatted string with the traceback info.
335
335
336 Parameters
336 Parameters
337 ----------
337 ----------
338 etype : exception type
338 etype : exception type
339 Type of the exception raised.
339 Type of the exception raised.
340 evalue : object
340 evalue : object
341 Data stored in the exception
341 Data stored in the exception
342 etb : object
342 etb : object
343 If list: List of frames, see class docstring for details.
343 If list: List of frames, see class docstring for details.
344 If Traceback: Traceback of the exception.
344 If Traceback: Traceback of the exception.
345 tb_offset : int, optional
345 tb_offset : int, optional
346 Number of frames in the traceback to skip. If not given, the
346 Number of frames in the traceback to skip. If not given, the
347 instance evalue is used (set in constructor).
347 instance evalue is used (set in constructor).
348 context : int, optional
348 context : int, optional
349 Number of lines of context information to print.
349 Number of lines of context information to print.
350
350
351 Returns
351 Returns
352 -------
352 -------
353 String with formatted exception.
353 String with formatted exception.
354 """
354 """
355 # This is a workaround to get chained_exc_ids in recursive calls
355 # This is a workaround to get chained_exc_ids in recursive calls
356 # etb should not be a tuple if structured_traceback is not recursive
356 # etb should not be a tuple if structured_traceback is not recursive
357 if isinstance(etb, tuple):
357 if isinstance(etb, tuple):
358 etb, chained_exc_ids = etb
358 etb, chained_exc_ids = etb
359 else:
359 else:
360 chained_exc_ids = set()
360 chained_exc_ids = set()
361
361
362 if isinstance(etb, list):
362 if isinstance(etb, list):
363 elist = etb
363 elist = etb
364 elif etb is not None:
364 elif etb is not None:
365 elist = self._extract_tb(etb)
365 elist = self._extract_tb(etb)
366 else:
366 else:
367 elist = []
367 elist = []
368 tb_offset = self.tb_offset if tb_offset is None else tb_offset
368 tb_offset = self.tb_offset if tb_offset is None else tb_offset
369 Colors = self.Colors
369 Colors = self.Colors
370 out_list = []
370 out_list = []
371 if elist:
371 if elist:
372
372
373 if tb_offset and len(elist) > tb_offset:
373 if tb_offset and len(elist) > tb_offset:
374 elist = elist[tb_offset:]
374 elist = elist[tb_offset:]
375
375
376 out_list.append('Traceback %s(most recent call last)%s:' %
376 out_list.append('Traceback %s(most recent call last)%s:' %
377 (Colors.normalEm, Colors.Normal) + '\n')
377 (Colors.normalEm, Colors.Normal) + '\n')
378 out_list.extend(self._format_list(elist))
378 out_list.extend(self._format_list(elist))
379 # The exception info should be a single entry in the list.
379 # The exception info should be a single entry in the list.
380 lines = ''.join(self._format_exception_only(etype, evalue))
380 lines = ''.join(self._format_exception_only(etype, evalue))
381 out_list.append(lines)
381 out_list.append(lines)
382
382
383 exception = self.get_parts_of_chained_exception(evalue)
383 exception = self.get_parts_of_chained_exception(evalue)
384
384
385 if exception and not id(exception[1]) in chained_exc_ids:
385 if exception and not id(exception[1]) in chained_exc_ids:
386 chained_exception_message = self.prepare_chained_exception_message(
386 chained_exception_message = self.prepare_chained_exception_message(
387 evalue.__cause__)[0]
387 evalue.__cause__)[0]
388 etype, evalue, etb = exception
388 etype, evalue, etb = exception
389 # Trace exception to avoid infinite 'cause' loop
389 # Trace exception to avoid infinite 'cause' loop
390 chained_exc_ids.add(id(exception[1]))
390 chained_exc_ids.add(id(exception[1]))
391 chained_exceptions_tb_offset = 0
391 chained_exceptions_tb_offset = 0
392 out_list = (
392 out_list = (
393 self.structured_traceback(
393 self.structured_traceback(
394 etype, evalue, (etb, chained_exc_ids),
394 etype, evalue, (etb, chained_exc_ids),
395 chained_exceptions_tb_offset, context)
395 chained_exceptions_tb_offset, context)
396 + chained_exception_message
396 + chained_exception_message
397 + out_list)
397 + out_list)
398
398
399 return out_list
399 return out_list
400
400
401 def _format_list(self, extracted_list):
401 def _format_list(self, extracted_list):
402 """Format a list of traceback entry tuples for printing.
402 """Format a list of traceback entry tuples for printing.
403
403
404 Given a list of tuples as returned by extract_tb() or
404 Given a list of tuples as returned by extract_tb() or
405 extract_stack(), return a list of strings ready for printing.
405 extract_stack(), return a list of strings ready for printing.
406 Each string in the resulting list corresponds to the item with the
406 Each string in the resulting list corresponds to the item with the
407 same index in the argument list. Each string ends in a newline;
407 same index in the argument list. Each string ends in a newline;
408 the strings may contain internal newlines as well, for those items
408 the strings may contain internal newlines as well, for those items
409 whose source text line is not None.
409 whose source text line is not None.
410
410
411 Lifted almost verbatim from traceback.py
411 Lifted almost verbatim from traceback.py
412 """
412 """
413
413
414 Colors = self.Colors
414 Colors = self.Colors
415 list = []
415 list = []
416 for filename, lineno, name, line in extracted_list[:-1]:
416 for filename, lineno, name, line in extracted_list[:-1]:
417 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
417 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
418 (Colors.filename, filename, Colors.Normal,
418 (Colors.filename, filename, Colors.Normal,
419 Colors.lineno, lineno, Colors.Normal,
419 Colors.lineno, lineno, Colors.Normal,
420 Colors.name, name, Colors.Normal)
420 Colors.name, name, Colors.Normal)
421 if line:
421 if line:
422 item += ' %s\n' % line.strip()
422 item += ' %s\n' % line.strip()
423 list.append(item)
423 list.append(item)
424 # Emphasize the last entry
424 # Emphasize the last entry
425 filename, lineno, name, line = extracted_list[-1]
425 filename, lineno, name, line = extracted_list[-1]
426 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
426 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
427 (Colors.normalEm,
427 (Colors.normalEm,
428 Colors.filenameEm, filename, Colors.normalEm,
428 Colors.filenameEm, filename, Colors.normalEm,
429 Colors.linenoEm, lineno, Colors.normalEm,
429 Colors.linenoEm, lineno, Colors.normalEm,
430 Colors.nameEm, name, Colors.normalEm,
430 Colors.nameEm, name, Colors.normalEm,
431 Colors.Normal)
431 Colors.Normal)
432 if line:
432 if line:
433 item += '%s %s%s\n' % (Colors.line, line.strip(),
433 item += '%s %s%s\n' % (Colors.line, line.strip(),
434 Colors.Normal)
434 Colors.Normal)
435 list.append(item)
435 list.append(item)
436 return list
436 return list
437
437
438 def _format_exception_only(self, etype, value):
438 def _format_exception_only(self, etype, value):
439 """Format the exception part of a traceback.
439 """Format the exception part of a traceback.
440
440
441 The arguments are the exception type and value such as given by
441 The arguments are the exception type and value such as given by
442 sys.exc_info()[:2]. The return value is a list of strings, each ending
442 sys.exc_info()[:2]. The return value is a list of strings, each ending
443 in a newline. Normally, the list contains a single string; however,
443 in a newline. Normally, the list contains a single string; however,
444 for SyntaxError exceptions, it contains several lines that (when
444 for SyntaxError exceptions, it contains several lines that (when
445 printed) display detailed information about where the syntax error
445 printed) display detailed information about where the syntax error
446 occurred. The message indicating which exception occurred is the
446 occurred. The message indicating which exception occurred is the
447 always last string in the list.
447 always last string in the list.
448
448
449 Also lifted nearly verbatim from traceback.py
449 Also lifted nearly verbatim from traceback.py
450 """
450 """
451 have_filedata = False
451 have_filedata = False
452 Colors = self.Colors
452 Colors = self.Colors
453 list = []
453 list = []
454 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
454 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
455 if value is None:
455 if value is None:
456 # Not sure if this can still happen in Python 2.6 and above
456 # Not sure if this can still happen in Python 2.6 and above
457 list.append(stype + '\n')
457 list.append(stype + '\n')
458 else:
458 else:
459 if issubclass(etype, SyntaxError):
459 if issubclass(etype, SyntaxError):
460 have_filedata = True
460 have_filedata = True
461 if not value.filename: value.filename = "<string>"
461 if not value.filename: value.filename = "<string>"
462 if value.lineno:
462 if value.lineno:
463 lineno = value.lineno
463 lineno = value.lineno
464 textline = linecache.getline(value.filename, value.lineno)
464 textline = linecache.getline(value.filename, value.lineno)
465 else:
465 else:
466 lineno = 'unknown'
466 lineno = 'unknown'
467 textline = ''
467 textline = ''
468 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
468 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
469 (Colors.normalEm,
469 (Colors.normalEm,
470 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
470 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
471 Colors.linenoEm, lineno, Colors.Normal ))
471 Colors.linenoEm, lineno, Colors.Normal ))
472 if textline == '':
472 if textline == '':
473 textline = py3compat.cast_unicode(value.text, "utf-8")
473 textline = py3compat.cast_unicode(value.text, "utf-8")
474
474
475 if textline is not None:
475 if textline is not None:
476 i = 0
476 i = 0
477 while i < len(textline) and textline[i].isspace():
477 while i < len(textline) and textline[i].isspace():
478 i += 1
478 i += 1
479 list.append('%s %s%s\n' % (Colors.line,
479 list.append('%s %s%s\n' % (Colors.line,
480 textline.strip(),
480 textline.strip(),
481 Colors.Normal))
481 Colors.Normal))
482 if value.offset is not None:
482 if value.offset is not None:
483 s = ' '
483 s = ' '
484 for c in textline[i:value.offset - 1]:
484 for c in textline[i:value.offset - 1]:
485 if c.isspace():
485 if c.isspace():
486 s += c
486 s += c
487 else:
487 else:
488 s += ' '
488 s += ' '
489 list.append('%s%s^%s\n' % (Colors.caret, s,
489 list.append('%s%s^%s\n' % (Colors.caret, s,
490 Colors.Normal))
490 Colors.Normal))
491
491
492 try:
492 try:
493 s = value.msg
493 s = value.msg
494 except Exception:
494 except Exception:
495 s = self._some_str(value)
495 s = self._some_str(value)
496 if s:
496 if s:
497 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
497 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
498 Colors.Normal, s))
498 Colors.Normal, s))
499 else:
499 else:
500 list.append('%s\n' % stype)
500 list.append('%s\n' % stype)
501
501
502 # sync with user hooks
502 # sync with user hooks
503 if have_filedata:
503 if have_filedata:
504 ipinst = get_ipython()
504 ipinst = get_ipython()
505 if ipinst is not None:
505 if ipinst is not None:
506 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
506 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
507
507
508 return list
508 return list
509
509
510 def get_exception_only(self, etype, value):
510 def get_exception_only(self, etype, value):
511 """Only print the exception type and message, without a traceback.
511 """Only print the exception type and message, without a traceback.
512
512
513 Parameters
513 Parameters
514 ----------
514 ----------
515 etype : exception type
515 etype : exception type
516 evalue : exception value
516 evalue : exception value
517 """
517 """
518 return ListTB.structured_traceback(self, etype, value)
518 return ListTB.structured_traceback(self, etype, value)
519
519
520 def show_exception_only(self, etype, evalue):
520 def show_exception_only(self, etype, evalue):
521 """Only print the exception type and message, without a traceback.
521 """Only print the exception type and message, without a traceback.
522
522
523 Parameters
523 Parameters
524 ----------
524 ----------
525 etype : exception type
525 etype : exception type
526 evalue : exception value
526 evalue : exception value
527 """
527 """
528 # This method needs to use __call__ from *this* class, not the one from
528 # This method needs to use __call__ from *this* class, not the one from
529 # a subclass whose signature or behavior may be different
529 # a subclass whose signature or behavior may be different
530 ostream = self.ostream
530 ostream = self.ostream
531 ostream.flush()
531 ostream.flush()
532 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
532 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
533 ostream.flush()
533 ostream.flush()
534
534
535 def _some_str(self, value):
535 def _some_str(self, value):
536 # Lifted from traceback.py
536 # Lifted from traceback.py
537 try:
537 try:
538 return py3compat.cast_unicode(str(value))
538 return py3compat.cast_unicode(str(value))
539 except:
539 except:
540 return u'<unprintable %s object>' % type(value).__name__
540 return u'<unprintable %s object>' % type(value).__name__
541
541
542
542
543 #----------------------------------------------------------------------------
543 #----------------------------------------------------------------------------
544 class VerboseTB(TBTools):
544 class VerboseTB(TBTools):
545 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
545 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
546 of HTML. Requires inspect and pydoc. Crazy, man.
546 of HTML. Requires inspect and pydoc. Crazy, man.
547
547
548 Modified version which optionally strips the topmost entries from the
548 Modified version which optionally strips the topmost entries from the
549 traceback, to be used with alternate interpreters (because their own code
549 traceback, to be used with alternate interpreters (because their own code
550 would appear in the traceback)."""
550 would appear in the traceback)."""
551
551
552 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
552 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
553 tb_offset=0, long_header=False, include_vars=True,
553 tb_offset=0, long_header=False, include_vars=True,
554 check_cache=None, debugger_cls = None,
554 check_cache=None, debugger_cls = None,
555 parent=None, config=None):
555 parent=None, config=None):
556 """Specify traceback offset, headers and color scheme.
556 """Specify traceback offset, headers and color scheme.
557
557
558 Define how many frames to drop from the tracebacks. Calling it with
558 Define how many frames to drop from the tracebacks. Calling it with
559 tb_offset=1 allows use of this handler in interpreters which will have
559 tb_offset=1 allows use of this handler in interpreters which will have
560 their own code at the top of the traceback (VerboseTB will first
560 their own code at the top of the traceback (VerboseTB will first
561 remove that frame before printing the traceback info)."""
561 remove that frame before printing the traceback info)."""
562 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
562 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
563 ostream=ostream, parent=parent, config=config)
563 ostream=ostream, parent=parent, config=config)
564 self.tb_offset = tb_offset
564 self.tb_offset = tb_offset
565 self.long_header = long_header
565 self.long_header = long_header
566 self.include_vars = include_vars
566 self.include_vars = include_vars
567 # By default we use linecache.checkcache, but the user can provide a
567 # By default we use linecache.checkcache, but the user can provide a
568 # different check_cache implementation. This is used by the IPython
568 # different check_cache implementation. This is used by the IPython
569 # kernel to provide tracebacks for interactive code that is cached,
569 # kernel to provide tracebacks for interactive code that is cached,
570 # by a compiler instance that flushes the linecache but preserves its
570 # by a compiler instance that flushes the linecache but preserves its
571 # own code cache.
571 # own code cache.
572 if check_cache is None:
572 if check_cache is None:
573 check_cache = linecache.checkcache
573 check_cache = linecache.checkcache
574 self.check_cache = check_cache
574 self.check_cache = check_cache
575
575
576 self.debugger_cls = debugger_cls or debugger.Pdb
576 self.debugger_cls = debugger_cls or debugger.Pdb
577 self.skip_hidden = True
577 self.skip_hidden = True
578
578
579 def format_record(self, frame_info):
579 def format_record(self, frame_info):
580 """Format a single stack frame"""
580 """Format a single stack frame"""
581 Colors = self.Colors # just a shorthand + quicker name lookup
581 Colors = self.Colors # just a shorthand + quicker name lookup
582 ColorsNormal = Colors.Normal # used a lot
582 ColorsNormal = Colors.Normal # used a lot
583
583
584
585
586 if isinstance(frame_info, stack_data.RepeatedFrames):
584 if isinstance(frame_info, stack_data.RepeatedFrames):
587 return ' %s[... skipping similar frames: %s]%s\n' % (
585 return ' %s[... skipping similar frames: %s]%s\n' % (
588 Colors.excName, frame_info.description, ColorsNormal)
586 Colors.excName, frame_info.description, ColorsNormal)
589
587
588 file = frame_info.filename
589
590 ipinst = get_ipython()
591 if ipinst is not None and file in ipinst.compile._filename_map:
592 file = "[%s]" % ipinst.compile._filename_map[file]
593 tpl_link = "In %s%%s%s," % (Colors.filenameEm, ColorsNormal)
594 else:
595 file = util_path.compress_user(
596 py3compat.cast_unicode(file, util_path.fs_encoding)
597 )
598 tpl_link = "File %s%%s%s," % (Colors.filenameEm, ColorsNormal)
599
590 indent = ' ' * INDENT_SIZE
600 indent = ' ' * INDENT_SIZE
591 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
601 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
592 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
593 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
602 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
594 ColorsNormal)
603 ColorsNormal)
595 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
604 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
596 (Colors.vName, Colors.valEm, ColorsNormal)
605 (Colors.vName, Colors.valEm, ColorsNormal)
597 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
598 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
606 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
599
607
600 file = frame_info.filename
608 link = tpl_link % file
601 file = py3compat.cast_unicode(file, util_path.fs_encoding)
602 link = tpl_link % util_path.compress_user(file)
603 args, varargs, varkw, locals_ = inspect.getargvalues(frame_info.frame)
609 args, varargs, varkw, locals_ = inspect.getargvalues(frame_info.frame)
604
610
605 func = frame_info.executing.code_qualname()
611 func = frame_info.executing.code_qualname()
606 if func == '<module>':
612 if func == '<module>':
607 call = tpl_call % (func, '')
613 call = tpl_call % (func, '')
608 else:
614 else:
609 # Decide whether to include variable details or not
615 # Decide whether to include variable details or not
610 var_repr = eqrepr if self.include_vars else nullrepr
616 var_repr = eqrepr if self.include_vars else nullrepr
611 try:
617 try:
612 call = tpl_call % (func, inspect.formatargvalues(args,
618 call = tpl_call % (func, inspect.formatargvalues(args,
613 varargs, varkw,
619 varargs, varkw,
614 locals_, formatvalue=var_repr))
620 locals_, formatvalue=var_repr))
615 except KeyError:
621 except KeyError:
616 # This happens in situations like errors inside generator
622 # This happens in situations like errors inside generator
617 # expressions, where local variables are listed in the
623 # expressions, where local variables are listed in the
618 # line, but can't be extracted from the frame. I'm not
624 # line, but can't be extracted from the frame. I'm not
619 # 100% sure this isn't actually a bug in inspect itself,
625 # 100% sure this isn't actually a bug in inspect itself,
620 # but since there's no info for us to compute with, the
626 # but since there's no info for us to compute with, the
621 # best we can do is report the failure and move on. Here
627 # best we can do is report the failure and move on. Here
622 # we must *not* call any traceback construction again,
628 # we must *not* call any traceback construction again,
623 # because that would mess up use of %debug later on. So we
629 # because that would mess up use of %debug later on. So we
624 # simply report the failure and move on. The only
630 # simply report the failure and move on. The only
625 # limitation will be that this frame won't have locals
631 # limitation will be that this frame won't have locals
626 # listed in the call signature. Quite subtle problem...
632 # listed in the call signature. Quite subtle problem...
627 # I can't think of a good way to validate this in a unit
633 # I can't think of a good way to validate this in a unit
628 # test, but running a script consisting of:
634 # test, but running a script consisting of:
629 # dict( (k,v.strip()) for (k,v) in range(10) )
635 # dict( (k,v.strip()) for (k,v) in range(10) )
630 # will illustrate the error, if this exception catch is
636 # will illustrate the error, if this exception catch is
631 # disabled.
637 # disabled.
632 call = tpl_call_fail % func
638 call = tpl_call_fail % func
633
639
634 lvals = ''
640 lvals = ''
635 lvals_list = []
641 lvals_list = []
636 if self.include_vars:
642 if self.include_vars:
637 for var in frame_info.variables_in_executing_piece:
643 for var in frame_info.variables_in_executing_piece:
638 lvals_list.append(tpl_name_val % (var.name, repr(var.value)))
644 lvals_list.append(tpl_name_val % (var.name, repr(var.value)))
639 if lvals_list:
645 if lvals_list:
640 lvals = '%s%s' % (indent, em_normal.join(lvals_list))
646 lvals = '%s%s' % (indent, em_normal.join(lvals_list))
641
647
642 result = '%s %s\n' % (link, call)
648 result = '%s %s\n' % (link, call)
643
649
644 result += ''.join(_format_traceback_lines(frame_info.lines, Colors, self.has_colors, lvals))
650 result += ''.join(_format_traceback_lines(frame_info.lines, Colors, self.has_colors, lvals))
645 return result
651 return result
646
652
647 def prepare_header(self, etype, long_version=False):
653 def prepare_header(self, etype, long_version=False):
648 colors = self.Colors # just a shorthand + quicker name lookup
654 colors = self.Colors # just a shorthand + quicker name lookup
649 colorsnormal = colors.Normal # used a lot
655 colorsnormal = colors.Normal # used a lot
650 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
656 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
651 width = min(75, get_terminal_size()[0])
657 width = min(75, get_terminal_size()[0])
652 if long_version:
658 if long_version:
653 # Header with the exception type, python version, and date
659 # Header with the exception type, python version, and date
654 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
660 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
655 date = time.ctime(time.time())
661 date = time.ctime(time.time())
656
662
657 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
663 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
658 exc, ' ' * (width - len(str(etype)) - len(pyver)),
664 exc, ' ' * (width - len(str(etype)) - len(pyver)),
659 pyver, date.rjust(width) )
665 pyver, date.rjust(width) )
660 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
666 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
661 "\ncalls leading up to the error, with the most recent (innermost) call last."
667 "\ncalls leading up to the error, with the most recent (innermost) call last."
662 else:
668 else:
663 # Simplified header
669 # Simplified header
664 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
670 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
665 rjust(width - len(str(etype))) )
671 rjust(width - len(str(etype))) )
666
672
667 return head
673 return head
668
674
669 def format_exception(self, etype, evalue):
675 def format_exception(self, etype, evalue):
670 colors = self.Colors # just a shorthand + quicker name lookup
676 colors = self.Colors # just a shorthand + quicker name lookup
671 colorsnormal = colors.Normal # used a lot
677 colorsnormal = colors.Normal # used a lot
672 # Get (safely) a string form of the exception info
678 # Get (safely) a string form of the exception info
673 try:
679 try:
674 etype_str, evalue_str = map(str, (etype, evalue))
680 etype_str, evalue_str = map(str, (etype, evalue))
675 except:
681 except:
676 # User exception is improperly defined.
682 # User exception is improperly defined.
677 etype, evalue = str, sys.exc_info()[:2]
683 etype, evalue = str, sys.exc_info()[:2]
678 etype_str, evalue_str = map(str, (etype, evalue))
684 etype_str, evalue_str = map(str, (etype, evalue))
679 # ... and format it
685 # ... and format it
680 return ['%s%s%s: %s' % (colors.excName, etype_str,
686 return ['%s%s%s: %s' % (colors.excName, etype_str,
681 colorsnormal, py3compat.cast_unicode(evalue_str))]
687 colorsnormal, py3compat.cast_unicode(evalue_str))]
682
688
683 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
689 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
684 """Formats the header, traceback and exception message for a single exception.
690 """Formats the header, traceback and exception message for a single exception.
685
691
686 This may be called multiple times by Python 3 exception chaining
692 This may be called multiple times by Python 3 exception chaining
687 (PEP 3134).
693 (PEP 3134).
688 """
694 """
689 # some locals
695 # some locals
690 orig_etype = etype
696 orig_etype = etype
691 try:
697 try:
692 etype = etype.__name__
698 etype = etype.__name__
693 except AttributeError:
699 except AttributeError:
694 pass
700 pass
695
701
696 tb_offset = self.tb_offset if tb_offset is None else tb_offset
702 tb_offset = self.tb_offset if tb_offset is None else tb_offset
697 head = self.prepare_header(etype, self.long_header)
703 head = self.prepare_header(etype, self.long_header)
698 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
704 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
699
705
700 frames = []
706 frames = []
701 skipped = 0
707 skipped = 0
702 lastrecord = len(records) - 1
708 lastrecord = len(records) - 1
703 for i, r in enumerate(records):
709 for i, r in enumerate(records):
704 if not isinstance(r, stack_data.RepeatedFrames) and self.skip_hidden:
710 if not isinstance(r, stack_data.RepeatedFrames) and self.skip_hidden:
705 if r.frame.f_locals.get("__tracebackhide__", 0) and i != lastrecord:
711 if r.frame.f_locals.get("__tracebackhide__", 0) and i != lastrecord:
706 skipped += 1
712 skipped += 1
707 continue
713 continue
708 if skipped:
714 if skipped:
709 Colors = self.Colors # just a shorthand + quicker name lookup
715 Colors = self.Colors # just a shorthand + quicker name lookup
710 ColorsNormal = Colors.Normal # used a lot
716 ColorsNormal = Colors.Normal # used a lot
711 frames.append(
717 frames.append(
712 " %s[... skipping hidden %s frame]%s\n"
718 " %s[... skipping hidden %s frame]%s\n"
713 % (Colors.excName, skipped, ColorsNormal)
719 % (Colors.excName, skipped, ColorsNormal)
714 )
720 )
715 skipped = 0
721 skipped = 0
716 frames.append(self.format_record(r))
722 frames.append(self.format_record(r))
717 if skipped:
723 if skipped:
718 Colors = self.Colors # just a shorthand + quicker name lookup
724 Colors = self.Colors # just a shorthand + quicker name lookup
719 ColorsNormal = Colors.Normal # used a lot
725 ColorsNormal = Colors.Normal # used a lot
720 frames.append(
726 frames.append(
721 " %s[... skipping hidden %s frame]%s\n"
727 " %s[... skipping hidden %s frame]%s\n"
722 % (Colors.excName, skipped, ColorsNormal)
728 % (Colors.excName, skipped, ColorsNormal)
723 )
729 )
724
730
725 formatted_exception = self.format_exception(etype, evalue)
731 formatted_exception = self.format_exception(etype, evalue)
726 if records:
732 if records:
727 frame_info = records[-1]
733 frame_info = records[-1]
728 ipinst = get_ipython()
734 ipinst = get_ipython()
729 if ipinst is not None:
735 if ipinst is not None:
730 ipinst.hooks.synchronize_with_editor(frame_info.filename, frame_info.lineno, 0)
736 ipinst.hooks.synchronize_with_editor(frame_info.filename, frame_info.lineno, 0)
731
737
732 return [[head] + frames + [''.join(formatted_exception[0])]]
738 return [[head] + frames + [''.join(formatted_exception[0])]]
733
739
734 def get_records(self, etb, number_of_lines_of_context, tb_offset):
740 def get_records(self, etb, number_of_lines_of_context, tb_offset):
735 context = number_of_lines_of_context - 1
741 context = number_of_lines_of_context - 1
736 after = context // 2
742 after = context // 2
737 before = context - after
743 before = context - after
738 if self.has_colors:
744 if self.has_colors:
739 style = get_style_by_name('default')
745 style = get_style_by_name('default')
740 style = stack_data.style_with_executing_node(style, 'bg:#00005f')
746 style = stack_data.style_with_executing_node(style, 'bg:#00005f')
741 formatter = Terminal256Formatter(style=style)
747 formatter = Terminal256Formatter(style=style)
742 else:
748 else:
743 formatter = None
749 formatter = None
744 options = stack_data.Options(
750 options = stack_data.Options(
745 before=before,
751 before=before,
746 after=after,
752 after=after,
747 pygments_formatter=formatter,
753 pygments_formatter=formatter,
748 )
754 )
749 return list(stack_data.FrameInfo.stack_data(etb, options=options))[tb_offset:]
755 return list(stack_data.FrameInfo.stack_data(etb, options=options))[tb_offset:]
750
756
751 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
757 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
752 number_of_lines_of_context=5):
758 number_of_lines_of_context=5):
753 """Return a nice text document describing the traceback."""
759 """Return a nice text document describing the traceback."""
754
760
755 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
761 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
756 tb_offset)
762 tb_offset)
757
763
758 colors = self.Colors # just a shorthand + quicker name lookup
764 colors = self.Colors # just a shorthand + quicker name lookup
759 colorsnormal = colors.Normal # used a lot
765 colorsnormal = colors.Normal # used a lot
760 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
766 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
761 structured_traceback_parts = [head]
767 structured_traceback_parts = [head]
762 chained_exceptions_tb_offset = 0
768 chained_exceptions_tb_offset = 0
763 lines_of_context = 3
769 lines_of_context = 3
764 formatted_exceptions = formatted_exception
770 formatted_exceptions = formatted_exception
765 exception = self.get_parts_of_chained_exception(evalue)
771 exception = self.get_parts_of_chained_exception(evalue)
766 if exception:
772 if exception:
767 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
773 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
768 etype, evalue, etb = exception
774 etype, evalue, etb = exception
769 else:
775 else:
770 evalue = None
776 evalue = None
771 chained_exc_ids = set()
777 chained_exc_ids = set()
772 while evalue:
778 while evalue:
773 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
779 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
774 chained_exceptions_tb_offset)
780 chained_exceptions_tb_offset)
775 exception = self.get_parts_of_chained_exception(evalue)
781 exception = self.get_parts_of_chained_exception(evalue)
776
782
777 if exception and not id(exception[1]) in chained_exc_ids:
783 if exception and not id(exception[1]) in chained_exc_ids:
778 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
784 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
779 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
785 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
780 etype, evalue, etb = exception
786 etype, evalue, etb = exception
781 else:
787 else:
782 evalue = None
788 evalue = None
783
789
784 # we want to see exceptions in a reversed order:
790 # we want to see exceptions in a reversed order:
785 # the first exception should be on top
791 # the first exception should be on top
786 for formatted_exception in reversed(formatted_exceptions):
792 for formatted_exception in reversed(formatted_exceptions):
787 structured_traceback_parts += formatted_exception
793 structured_traceback_parts += formatted_exception
788
794
789 return structured_traceback_parts
795 return structured_traceback_parts
790
796
791 def debugger(self, force=False):
797 def debugger(self, force=False):
792 """Call up the pdb debugger if desired, always clean up the tb
798 """Call up the pdb debugger if desired, always clean up the tb
793 reference.
799 reference.
794
800
795 Keywords:
801 Keywords:
796
802
797 - force(False): by default, this routine checks the instance call_pdb
803 - force(False): by default, this routine checks the instance call_pdb
798 flag and does not actually invoke the debugger if the flag is false.
804 flag and does not actually invoke the debugger if the flag is false.
799 The 'force' option forces the debugger to activate even if the flag
805 The 'force' option forces the debugger to activate even if the flag
800 is false.
806 is false.
801
807
802 If the call_pdb flag is set, the pdb interactive debugger is
808 If the call_pdb flag is set, the pdb interactive debugger is
803 invoked. In all cases, the self.tb reference to the current traceback
809 invoked. In all cases, the self.tb reference to the current traceback
804 is deleted to prevent lingering references which hamper memory
810 is deleted to prevent lingering references which hamper memory
805 management.
811 management.
806
812
807 Note that each call to pdb() does an 'import readline', so if your app
813 Note that each call to pdb() does an 'import readline', so if your app
808 requires a special setup for the readline completers, you'll have to
814 requires a special setup for the readline completers, you'll have to
809 fix that by hand after invoking the exception handler."""
815 fix that by hand after invoking the exception handler."""
810
816
811 if force or self.call_pdb:
817 if force or self.call_pdb:
812 if self.pdb is None:
818 if self.pdb is None:
813 self.pdb = self.debugger_cls()
819 self.pdb = self.debugger_cls()
814 # the system displayhook may have changed, restore the original
820 # the system displayhook may have changed, restore the original
815 # for pdb
821 # for pdb
816 display_trap = DisplayTrap(hook=sys.__displayhook__)
822 display_trap = DisplayTrap(hook=sys.__displayhook__)
817 with display_trap:
823 with display_trap:
818 self.pdb.reset()
824 self.pdb.reset()
819 # Find the right frame so we don't pop up inside ipython itself
825 # Find the right frame so we don't pop up inside ipython itself
820 if hasattr(self, 'tb') and self.tb is not None:
826 if hasattr(self, 'tb') and self.tb is not None:
821 etb = self.tb
827 etb = self.tb
822 else:
828 else:
823 etb = self.tb = sys.last_traceback
829 etb = self.tb = sys.last_traceback
824 while self.tb is not None and self.tb.tb_next is not None:
830 while self.tb is not None and self.tb.tb_next is not None:
825 self.tb = self.tb.tb_next
831 self.tb = self.tb.tb_next
826 if etb and etb.tb_next:
832 if etb and etb.tb_next:
827 etb = etb.tb_next
833 etb = etb.tb_next
828 self.pdb.botframe = etb.tb_frame
834 self.pdb.botframe = etb.tb_frame
829 self.pdb.interaction(None, etb)
835 self.pdb.interaction(None, etb)
830
836
831 if hasattr(self, 'tb'):
837 if hasattr(self, 'tb'):
832 del self.tb
838 del self.tb
833
839
834 def handler(self, info=None):
840 def handler(self, info=None):
835 (etype, evalue, etb) = info or sys.exc_info()
841 (etype, evalue, etb) = info or sys.exc_info()
836 self.tb = etb
842 self.tb = etb
837 ostream = self.ostream
843 ostream = self.ostream
838 ostream.flush()
844 ostream.flush()
839 ostream.write(self.text(etype, evalue, etb))
845 ostream.write(self.text(etype, evalue, etb))
840 ostream.write('\n')
846 ostream.write('\n')
841 ostream.flush()
847 ostream.flush()
842
848
843 # Changed so an instance can just be called as VerboseTB_inst() and print
849 # Changed so an instance can just be called as VerboseTB_inst() and print
844 # out the right info on its own.
850 # out the right info on its own.
845 def __call__(self, etype=None, evalue=None, etb=None):
851 def __call__(self, etype=None, evalue=None, etb=None):
846 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
852 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
847 if etb is None:
853 if etb is None:
848 self.handler()
854 self.handler()
849 else:
855 else:
850 self.handler((etype, evalue, etb))
856 self.handler((etype, evalue, etb))
851 try:
857 try:
852 self.debugger()
858 self.debugger()
853 except KeyboardInterrupt:
859 except KeyboardInterrupt:
854 print("\nKeyboardInterrupt")
860 print("\nKeyboardInterrupt")
855
861
856
862
857 #----------------------------------------------------------------------------
863 #----------------------------------------------------------------------------
858 class FormattedTB(VerboseTB, ListTB):
864 class FormattedTB(VerboseTB, ListTB):
859 """Subclass ListTB but allow calling with a traceback.
865 """Subclass ListTB but allow calling with a traceback.
860
866
861 It can thus be used as a sys.excepthook for Python > 2.1.
867 It can thus be used as a sys.excepthook for Python > 2.1.
862
868
863 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
869 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
864
870
865 Allows a tb_offset to be specified. This is useful for situations where
871 Allows a tb_offset to be specified. This is useful for situations where
866 one needs to remove a number of topmost frames from the traceback (such as
872 one needs to remove a number of topmost frames from the traceback (such as
867 occurs with python programs that themselves execute other python code,
873 occurs with python programs that themselves execute other python code,
868 like Python shells). """
874 like Python shells). """
869
875
870 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
876 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
871 ostream=None,
877 ostream=None,
872 tb_offset=0, long_header=False, include_vars=False,
878 tb_offset=0, long_header=False, include_vars=False,
873 check_cache=None, debugger_cls=None,
879 check_cache=None, debugger_cls=None,
874 parent=None, config=None):
880 parent=None, config=None):
875
881
876 # NEVER change the order of this list. Put new modes at the end:
882 # NEVER change the order of this list. Put new modes at the end:
877 self.valid_modes = ['Plain', 'Context', 'Verbose', 'Minimal']
883 self.valid_modes = ['Plain', 'Context', 'Verbose', 'Minimal']
878 self.verbose_modes = self.valid_modes[1:3]
884 self.verbose_modes = self.valid_modes[1:3]
879
885
880 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
886 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
881 ostream=ostream, tb_offset=tb_offset,
887 ostream=ostream, tb_offset=tb_offset,
882 long_header=long_header, include_vars=include_vars,
888 long_header=long_header, include_vars=include_vars,
883 check_cache=check_cache, debugger_cls=debugger_cls,
889 check_cache=check_cache, debugger_cls=debugger_cls,
884 parent=parent, config=config)
890 parent=parent, config=config)
885
891
886 # Different types of tracebacks are joined with different separators to
892 # Different types of tracebacks are joined with different separators to
887 # form a single string. They are taken from this dict
893 # form a single string. They are taken from this dict
888 self._join_chars = dict(Plain='', Context='\n', Verbose='\n',
894 self._join_chars = dict(Plain='', Context='\n', Verbose='\n',
889 Minimal='')
895 Minimal='')
890 # set_mode also sets the tb_join_char attribute
896 # set_mode also sets the tb_join_char attribute
891 self.set_mode(mode)
897 self.set_mode(mode)
892
898
893 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
899 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
894 tb_offset = self.tb_offset if tb_offset is None else tb_offset
900 tb_offset = self.tb_offset if tb_offset is None else tb_offset
895 mode = self.mode
901 mode = self.mode
896 if mode in self.verbose_modes:
902 if mode in self.verbose_modes:
897 # Verbose modes need a full traceback
903 # Verbose modes need a full traceback
898 return VerboseTB.structured_traceback(
904 return VerboseTB.structured_traceback(
899 self, etype, value, tb, tb_offset, number_of_lines_of_context
905 self, etype, value, tb, tb_offset, number_of_lines_of_context
900 )
906 )
901 elif mode == 'Minimal':
907 elif mode == 'Minimal':
902 return ListTB.get_exception_only(self, etype, value)
908 return ListTB.get_exception_only(self, etype, value)
903 else:
909 else:
904 # We must check the source cache because otherwise we can print
910 # We must check the source cache because otherwise we can print
905 # out-of-date source code.
911 # out-of-date source code.
906 self.check_cache()
912 self.check_cache()
907 # Now we can extract and format the exception
913 # Now we can extract and format the exception
908 return ListTB.structured_traceback(
914 return ListTB.structured_traceback(
909 self, etype, value, tb, tb_offset, number_of_lines_of_context
915 self, etype, value, tb, tb_offset, number_of_lines_of_context
910 )
916 )
911
917
912 def stb2text(self, stb):
918 def stb2text(self, stb):
913 """Convert a structured traceback (a list) to a string."""
919 """Convert a structured traceback (a list) to a string."""
914 return self.tb_join_char.join(stb)
920 return self.tb_join_char.join(stb)
915
921
916
922
917 def set_mode(self, mode=None):
923 def set_mode(self, mode=None):
918 """Switch to the desired mode.
924 """Switch to the desired mode.
919
925
920 If mode is not specified, cycles through the available modes."""
926 If mode is not specified, cycles through the available modes."""
921
927
922 if not mode:
928 if not mode:
923 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
929 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
924 len(self.valid_modes)
930 len(self.valid_modes)
925 self.mode = self.valid_modes[new_idx]
931 self.mode = self.valid_modes[new_idx]
926 elif mode not in self.valid_modes:
932 elif mode not in self.valid_modes:
927 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
933 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
928 'Valid modes: ' + str(self.valid_modes))
934 'Valid modes: ' + str(self.valid_modes))
929 else:
935 else:
930 self.mode = mode
936 self.mode = mode
931 # include variable details only in 'Verbose' mode
937 # include variable details only in 'Verbose' mode
932 self.include_vars = (self.mode == self.valid_modes[2])
938 self.include_vars = (self.mode == self.valid_modes[2])
933 # Set the join character for generating text tracebacks
939 # Set the join character for generating text tracebacks
934 self.tb_join_char = self._join_chars[self.mode]
940 self.tb_join_char = self._join_chars[self.mode]
935
941
936 # some convenient shortcuts
942 # some convenient shortcuts
937 def plain(self):
943 def plain(self):
938 self.set_mode(self.valid_modes[0])
944 self.set_mode(self.valid_modes[0])
939
945
940 def context(self):
946 def context(self):
941 self.set_mode(self.valid_modes[1])
947 self.set_mode(self.valid_modes[1])
942
948
943 def verbose(self):
949 def verbose(self):
944 self.set_mode(self.valid_modes[2])
950 self.set_mode(self.valid_modes[2])
945
951
946 def minimal(self):
952 def minimal(self):
947 self.set_mode(self.valid_modes[3])
953 self.set_mode(self.valid_modes[3])
948
954
949
955
950 #----------------------------------------------------------------------------
956 #----------------------------------------------------------------------------
951 class AutoFormattedTB(FormattedTB):
957 class AutoFormattedTB(FormattedTB):
952 """A traceback printer which can be called on the fly.
958 """A traceback printer which can be called on the fly.
953
959
954 It will find out about exceptions by itself.
960 It will find out about exceptions by itself.
955
961
956 A brief example::
962 A brief example::
957
963
958 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
964 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
959 try:
965 try:
960 ...
966 ...
961 except:
967 except:
962 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
968 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
963 """
969 """
964
970
965 def __call__(self, etype=None, evalue=None, etb=None,
971 def __call__(self, etype=None, evalue=None, etb=None,
966 out=None, tb_offset=None):
972 out=None, tb_offset=None):
967 """Print out a formatted exception traceback.
973 """Print out a formatted exception traceback.
968
974
969 Optional arguments:
975 Optional arguments:
970 - out: an open file-like object to direct output to.
976 - out: an open file-like object to direct output to.
971
977
972 - tb_offset: the number of frames to skip over in the stack, on a
978 - tb_offset: the number of frames to skip over in the stack, on a
973 per-call basis (this overrides temporarily the instance's tb_offset
979 per-call basis (this overrides temporarily the instance's tb_offset
974 given at initialization time."""
980 given at initialization time."""
975
981
976 if out is None:
982 if out is None:
977 out = self.ostream
983 out = self.ostream
978 out.flush()
984 out.flush()
979 out.write(self.text(etype, evalue, etb, tb_offset))
985 out.write(self.text(etype, evalue, etb, tb_offset))
980 out.write('\n')
986 out.write('\n')
981 out.flush()
987 out.flush()
982 # FIXME: we should remove the auto pdb behavior from here and leave
988 # FIXME: we should remove the auto pdb behavior from here and leave
983 # that to the clients.
989 # that to the clients.
984 try:
990 try:
985 self.debugger()
991 self.debugger()
986 except KeyboardInterrupt:
992 except KeyboardInterrupt:
987 print("\nKeyboardInterrupt")
993 print("\nKeyboardInterrupt")
988
994
989 def structured_traceback(self, etype=None, value=None, tb=None,
995 def structured_traceback(self, etype=None, value=None, tb=None,
990 tb_offset=None, number_of_lines_of_context=5):
996 tb_offset=None, number_of_lines_of_context=5):
991 if etype is None:
997 if etype is None:
992 etype, value, tb = sys.exc_info()
998 etype, value, tb = sys.exc_info()
993 if isinstance(tb, tuple):
999 if isinstance(tb, tuple):
994 # tb is a tuple if this is a chained exception.
1000 # tb is a tuple if this is a chained exception.
995 self.tb = tb[0]
1001 self.tb = tb[0]
996 else:
1002 else:
997 self.tb = tb
1003 self.tb = tb
998 return FormattedTB.structured_traceback(
1004 return FormattedTB.structured_traceback(
999 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1005 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1000
1006
1001
1007
1002 #---------------------------------------------------------------------------
1008 #---------------------------------------------------------------------------
1003
1009
1004 # A simple class to preserve Nathan's original functionality.
1010 # A simple class to preserve Nathan's original functionality.
1005 class ColorTB(FormattedTB):
1011 class ColorTB(FormattedTB):
1006 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1012 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1007
1013
1008 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1014 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1009 FormattedTB.__init__(self, color_scheme=color_scheme,
1015 FormattedTB.__init__(self, color_scheme=color_scheme,
1010 call_pdb=call_pdb, **kwargs)
1016 call_pdb=call_pdb, **kwargs)
1011
1017
1012
1018
1013 class SyntaxTB(ListTB):
1019 class SyntaxTB(ListTB):
1014 """Extension which holds some state: the last exception value"""
1020 """Extension which holds some state: the last exception value"""
1015
1021
1016 def __init__(self, color_scheme='NoColor', parent=None, config=None):
1022 def __init__(self, color_scheme='NoColor', parent=None, config=None):
1017 ListTB.__init__(self, color_scheme, parent=parent, config=config)
1023 ListTB.__init__(self, color_scheme, parent=parent, config=config)
1018 self.last_syntax_error = None
1024 self.last_syntax_error = None
1019
1025
1020 def __call__(self, etype, value, elist):
1026 def __call__(self, etype, value, elist):
1021 self.last_syntax_error = value
1027 self.last_syntax_error = value
1022
1028
1023 ListTB.__call__(self, etype, value, elist)
1029 ListTB.__call__(self, etype, value, elist)
1024
1030
1025 def structured_traceback(self, etype, value, elist, tb_offset=None,
1031 def structured_traceback(self, etype, value, elist, tb_offset=None,
1026 context=5):
1032 context=5):
1027 # If the source file has been edited, the line in the syntax error can
1033 # If the source file has been edited, the line in the syntax error can
1028 # be wrong (retrieved from an outdated cache). This replaces it with
1034 # be wrong (retrieved from an outdated cache). This replaces it with
1029 # the current value.
1035 # the current value.
1030 if isinstance(value, SyntaxError) \
1036 if isinstance(value, SyntaxError) \
1031 and isinstance(value.filename, str) \
1037 and isinstance(value.filename, str) \
1032 and isinstance(value.lineno, int):
1038 and isinstance(value.lineno, int):
1033 linecache.checkcache(value.filename)
1039 linecache.checkcache(value.filename)
1034 newtext = linecache.getline(value.filename, value.lineno)
1040 newtext = linecache.getline(value.filename, value.lineno)
1035 if newtext:
1041 if newtext:
1036 value.text = newtext
1042 value.text = newtext
1037 self.last_syntax_error = value
1043 self.last_syntax_error = value
1038 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1044 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1039 tb_offset=tb_offset, context=context)
1045 tb_offset=tb_offset, context=context)
1040
1046
1041 def clear_err_state(self):
1047 def clear_err_state(self):
1042 """Return the current error state and clear it"""
1048 """Return the current error state and clear it"""
1043 e = self.last_syntax_error
1049 e = self.last_syntax_error
1044 self.last_syntax_error = None
1050 self.last_syntax_error = None
1045 return e
1051 return e
1046
1052
1047 def stb2text(self, stb):
1053 def stb2text(self, stb):
1048 """Convert a structured traceback (a list) to a string."""
1054 """Convert a structured traceback (a list) to a string."""
1049 return ''.join(stb)
1055 return ''.join(stb)
1050
1056
1051
1057
1052 # some internal-use functions
1058 # some internal-use functions
1053 def text_repr(value):
1059 def text_repr(value):
1054 """Hopefully pretty robust repr equivalent."""
1060 """Hopefully pretty robust repr equivalent."""
1055 # this is pretty horrible but should always return *something*
1061 # this is pretty horrible but should always return *something*
1056 try:
1062 try:
1057 return pydoc.text.repr(value)
1063 return pydoc.text.repr(value)
1058 except KeyboardInterrupt:
1064 except KeyboardInterrupt:
1059 raise
1065 raise
1060 except:
1066 except:
1061 try:
1067 try:
1062 return repr(value)
1068 return repr(value)
1063 except KeyboardInterrupt:
1069 except KeyboardInterrupt:
1064 raise
1070 raise
1065 except:
1071 except:
1066 try:
1072 try:
1067 # all still in an except block so we catch
1073 # all still in an except block so we catch
1068 # getattr raising
1074 # getattr raising
1069 name = getattr(value, '__name__', None)
1075 name = getattr(value, '__name__', None)
1070 if name:
1076 if name:
1071 # ick, recursion
1077 # ick, recursion
1072 return text_repr(name)
1078 return text_repr(name)
1073 klass = getattr(value, '__class__', None)
1079 klass = getattr(value, '__class__', None)
1074 if klass:
1080 if klass:
1075 return '%s instance' % text_repr(klass)
1081 return '%s instance' % text_repr(klass)
1076 except KeyboardInterrupt:
1082 except KeyboardInterrupt:
1077 raise
1083 raise
1078 except:
1084 except:
1079 return 'UNRECOVERABLE REPR FAILURE'
1085 return 'UNRECOVERABLE REPR FAILURE'
1080
1086
1081
1087
1082 def eqrepr(value, repr=text_repr):
1088 def eqrepr(value, repr=text_repr):
1083 return '=%s' % repr(value)
1089 return '=%s' % repr(value)
1084
1090
1085
1091
1086 def nullrepr(value, repr=text_repr):
1092 def nullrepr(value, repr=text_repr):
1087 return ''
1093 return ''
General Comments 0
You need to be logged in to leave comments. Login now