##// END OF EJS Templates
Merge pull request #11999 from impact27/plain_chained...
Matthias Bussonnier -
r25322:a4c0db7f merge
parent child Browse files
Show More
@@ -1,440 +1,459 b''
1 1 # encoding: utf-8
2 2 """Tests for IPython.core.ultratb
3 3 """
4 4 import io
5 5 import logging
6 6 import sys
7 7 import os.path
8 8 from textwrap import dedent
9 9 import traceback
10 10 import unittest
11 11 from unittest import mock
12 12
13 13 import IPython.core.ultratb as ultratb
14 14 from IPython.core.ultratb import ColorTB, VerboseTB, find_recursion
15 15
16 16
17 17 from IPython.testing import tools as tt
18 18 from IPython.testing.decorators import onlyif_unicode_paths
19 19 from IPython.utils.syspathcontext import prepended_to_syspath
20 20 from IPython.utils.tempdir import TemporaryDirectory
21 21
22 22 file_1 = """1
23 23 2
24 24 3
25 25 def f():
26 26 1/0
27 27 """
28 28
29 29 file_2 = """def f():
30 30 1/0
31 31 """
32 32
33 33
34 34 def recursionlimit(frames):
35 35 """
36 36 decorator to set the recursion limit temporarily
37 37 """
38 38
39 39 def inner(test_function):
40 40 def wrapper(*args, **kwargs):
41 41 _orig_rec_limit = ultratb._FRAME_RECURSION_LIMIT
42 42 ultratb._FRAME_RECURSION_LIMIT = 50
43 43
44 44 rl = sys.getrecursionlimit()
45 45 sys.setrecursionlimit(frames)
46 46 try:
47 47 return test_function(*args, **kwargs)
48 48 finally:
49 49 sys.setrecursionlimit(rl)
50 50 ultratb._FRAME_RECURSION_LIMIT = _orig_rec_limit
51 51
52 52 return wrapper
53 53
54 54 return inner
55 55
56 56
57 57 class ChangedPyFileTest(unittest.TestCase):
58 58 def test_changing_py_file(self):
59 59 """Traceback produced if the line where the error occurred is missing?
60 60
61 61 https://github.com/ipython/ipython/issues/1456
62 62 """
63 63 with TemporaryDirectory() as td:
64 64 fname = os.path.join(td, "foo.py")
65 65 with open(fname, "w") as f:
66 66 f.write(file_1)
67 67
68 68 with prepended_to_syspath(td):
69 69 ip.run_cell("import foo")
70 70
71 71 with tt.AssertPrints("ZeroDivisionError"):
72 72 ip.run_cell("foo.f()")
73 73
74 74 # Make the file shorter, so the line of the error is missing.
75 75 with open(fname, "w") as f:
76 76 f.write(file_2)
77 77
78 78 # For some reason, this was failing on the *second* call after
79 79 # changing the file, so we call f() twice.
80 80 with tt.AssertNotPrints("Internal Python error", channel='stderr'):
81 81 with tt.AssertPrints("ZeroDivisionError"):
82 82 ip.run_cell("foo.f()")
83 83 with tt.AssertPrints("ZeroDivisionError"):
84 84 ip.run_cell("foo.f()")
85 85
86 86 iso_8859_5_file = u'''# coding: iso-8859-5
87 87
88 88 def fail():
89 89 """Π΄Π±Π˜Π–"""
90 90 1/0 # Π΄Π±Π˜Π–
91 91 '''
92 92
93 93 class NonAsciiTest(unittest.TestCase):
94 94 @onlyif_unicode_paths
95 95 def test_nonascii_path(self):
96 96 # Non-ascii directory name as well.
97 97 with TemporaryDirectory(suffix=u'Γ©') as td:
98 98 fname = os.path.join(td, u"fooΓ©.py")
99 99 with open(fname, "w") as f:
100 100 f.write(file_1)
101 101
102 102 with prepended_to_syspath(td):
103 103 ip.run_cell("import foo")
104 104
105 105 with tt.AssertPrints("ZeroDivisionError"):
106 106 ip.run_cell("foo.f()")
107 107
108 108 def test_iso8859_5(self):
109 109 with TemporaryDirectory() as td:
110 110 fname = os.path.join(td, 'dfghjkl.py')
111 111
112 112 with io.open(fname, 'w', encoding='iso-8859-5') as f:
113 113 f.write(iso_8859_5_file)
114 114
115 115 with prepended_to_syspath(td):
116 116 ip.run_cell("from dfghjkl import fail")
117 117
118 118 with tt.AssertPrints("ZeroDivisionError"):
119 119 with tt.AssertPrints(u'Π΄Π±Π˜Π–', suppress=False):
120 120 ip.run_cell('fail()')
121 121
122 122 def test_nonascii_msg(self):
123 123 cell = u"raise Exception('Γ©')"
124 124 expected = u"Exception('Γ©')"
125 125 ip.run_cell("%xmode plain")
126 126 with tt.AssertPrints(expected):
127 127 ip.run_cell(cell)
128 128
129 129 ip.run_cell("%xmode verbose")
130 130 with tt.AssertPrints(expected):
131 131 ip.run_cell(cell)
132 132
133 133 ip.run_cell("%xmode context")
134 134 with tt.AssertPrints(expected):
135 135 ip.run_cell(cell)
136 136
137 137 ip.run_cell("%xmode minimal")
138 138 with tt.AssertPrints(u"Exception: Γ©"):
139 139 ip.run_cell(cell)
140 140
141 141 # Put this back into Context mode for later tests.
142 142 ip.run_cell("%xmode context")
143 143
144 144 class NestedGenExprTestCase(unittest.TestCase):
145 145 """
146 146 Regression test for the following issues:
147 147 https://github.com/ipython/ipython/issues/8293
148 148 https://github.com/ipython/ipython/issues/8205
149 149 """
150 150 def test_nested_genexpr(self):
151 151 code = dedent(
152 152 """\
153 153 class SpecificException(Exception):
154 154 pass
155 155
156 156 def foo(x):
157 157 raise SpecificException("Success!")
158 158
159 159 sum(sum(foo(x) for _ in [0]) for x in [0])
160 160 """
161 161 )
162 162 with tt.AssertPrints('SpecificException: Success!', suppress=False):
163 163 ip.run_cell(code)
164 164
165 165
166 166 indentationerror_file = """if True:
167 167 zoon()
168 168 """
169 169
170 170 class IndentationErrorTest(unittest.TestCase):
171 171 def test_indentationerror_shows_line(self):
172 172 # See issue gh-2398
173 173 with tt.AssertPrints("IndentationError"):
174 174 with tt.AssertPrints("zoon()", suppress=False):
175 175 ip.run_cell(indentationerror_file)
176 176
177 177 with TemporaryDirectory() as td:
178 178 fname = os.path.join(td, "foo.py")
179 179 with open(fname, "w") as f:
180 180 f.write(indentationerror_file)
181 181
182 182 with tt.AssertPrints("IndentationError"):
183 183 with tt.AssertPrints("zoon()", suppress=False):
184 184 ip.magic('run %s' % fname)
185 185
186 186 se_file_1 = """1
187 187 2
188 188 7/
189 189 """
190 190
191 191 se_file_2 = """7/
192 192 """
193 193
194 194 class SyntaxErrorTest(unittest.TestCase):
195 195 def test_syntaxerror_without_lineno(self):
196 196 with tt.AssertNotPrints("TypeError"):
197 197 with tt.AssertPrints("line unknown"):
198 198 ip.run_cell("raise SyntaxError()")
199 199
200 200 def test_syntaxerror_no_stacktrace_at_compile_time(self):
201 201 syntax_error_at_compile_time = """
202 202 def foo():
203 203 ..
204 204 """
205 205 with tt.AssertPrints("SyntaxError"):
206 206 ip.run_cell(syntax_error_at_compile_time)
207 207
208 208 with tt.AssertNotPrints("foo()"):
209 209 ip.run_cell(syntax_error_at_compile_time)
210 210
211 211 def test_syntaxerror_stacktrace_when_running_compiled_code(self):
212 212 syntax_error_at_runtime = """
213 213 def foo():
214 214 eval("..")
215 215
216 216 def bar():
217 217 foo()
218 218
219 219 bar()
220 220 """
221 221 with tt.AssertPrints("SyntaxError"):
222 222 ip.run_cell(syntax_error_at_runtime)
223 223 # Assert syntax error during runtime generate stacktrace
224 224 with tt.AssertPrints(["foo()", "bar()"]):
225 225 ip.run_cell(syntax_error_at_runtime)
226 226 del ip.user_ns['bar']
227 227 del ip.user_ns['foo']
228 228
229 229 def test_changing_py_file(self):
230 230 with TemporaryDirectory() as td:
231 231 fname = os.path.join(td, "foo.py")
232 232 with open(fname, 'w') as f:
233 233 f.write(se_file_1)
234 234
235 235 with tt.AssertPrints(["7/", "SyntaxError"]):
236 236 ip.magic("run " + fname)
237 237
238 238 # Modify the file
239 239 with open(fname, 'w') as f:
240 240 f.write(se_file_2)
241 241
242 242 # The SyntaxError should point to the correct line
243 243 with tt.AssertPrints(["7/", "SyntaxError"]):
244 244 ip.magic("run " + fname)
245 245
246 246 def test_non_syntaxerror(self):
247 247 # SyntaxTB may be called with an error other than a SyntaxError
248 248 # See e.g. gh-4361
249 249 try:
250 250 raise ValueError('QWERTY')
251 251 except ValueError:
252 252 with tt.AssertPrints('QWERTY'):
253 253 ip.showsyntaxerror()
254 254
255 255
256 256 class Python3ChainedExceptionsTest(unittest.TestCase):
257 257 DIRECT_CAUSE_ERROR_CODE = """
258 258 try:
259 259 x = 1 + 2
260 260 print(not_defined_here)
261 261 except Exception as e:
262 262 x += 55
263 263 x - 1
264 264 y = {}
265 265 raise KeyError('uh') from e
266 266 """
267 267
268 268 EXCEPTION_DURING_HANDLING_CODE = """
269 269 try:
270 270 x = 1 + 2
271 271 print(not_defined_here)
272 272 except Exception as e:
273 273 x += 55
274 274 x - 1
275 275 y = {}
276 276 raise KeyError('uh')
277 277 """
278 278
279 279 SUPPRESS_CHAINING_CODE = """
280 280 try:
281 281 1/0
282 282 except Exception:
283 283 raise ValueError("Yikes") from None
284 284 """
285 285
286 286 def test_direct_cause_error(self):
287 287 with tt.AssertPrints(["KeyError", "NameError", "direct cause"]):
288 288 ip.run_cell(self.DIRECT_CAUSE_ERROR_CODE)
289 289
290 290 def test_exception_during_handling_error(self):
291 291 with tt.AssertPrints(["KeyError", "NameError", "During handling"]):
292 292 ip.run_cell(self.EXCEPTION_DURING_HANDLING_CODE)
293 293
294 294 def test_suppress_exception_chaining(self):
295 295 with tt.AssertNotPrints("ZeroDivisionError"), \
296 296 tt.AssertPrints("ValueError", suppress=False):
297 297 ip.run_cell(self.SUPPRESS_CHAINING_CODE)
298 298
299 def test_plain_direct_cause_error(self):
300 with tt.AssertPrints(["KeyError", "NameError", "direct cause"]):
301 ip.run_cell("%xmode Plain")
302 ip.run_cell(self.DIRECT_CAUSE_ERROR_CODE)
303 ip.run_cell("%xmode Verbose")
304
305 def test_plain_exception_during_handling_error(self):
306 with tt.AssertPrints(["KeyError", "NameError", "During handling"]):
307 ip.run_cell("%xmode Plain")
308 ip.run_cell(self.EXCEPTION_DURING_HANDLING_CODE)
309 ip.run_cell("%xmode Verbose")
310
311 def test_plain_suppress_exception_chaining(self):
312 with tt.AssertNotPrints("ZeroDivisionError"), \
313 tt.AssertPrints("ValueError", suppress=False):
314 ip.run_cell("%xmode Plain")
315 ip.run_cell(self.SUPPRESS_CHAINING_CODE)
316 ip.run_cell("%xmode Verbose")
317
299 318
300 319 class RecursionTest(unittest.TestCase):
301 320 DEFINITIONS = """
302 321 def non_recurs():
303 322 1/0
304 323
305 324 def r1():
306 325 r1()
307 326
308 327 def r3a():
309 328 r3b()
310 329
311 330 def r3b():
312 331 r3c()
313 332
314 333 def r3c():
315 334 r3a()
316 335
317 336 def r3o1():
318 337 r3a()
319 338
320 339 def r3o2():
321 340 r3o1()
322 341 """
323 342 def setUp(self):
324 343 ip.run_cell(self.DEFINITIONS)
325 344
326 345 def test_no_recursion(self):
327 346 with tt.AssertNotPrints("frames repeated"):
328 347 ip.run_cell("non_recurs()")
329 348
330 349 @recursionlimit(150)
331 350 def test_recursion_one_frame(self):
332 351 with tt.AssertPrints("1 frames repeated"):
333 352 ip.run_cell("r1()")
334 353
335 354 @recursionlimit(150)
336 355 def test_recursion_three_frames(self):
337 356 with tt.AssertPrints("3 frames repeated"):
338 357 ip.run_cell("r3o2()")
339 358
340 359 @recursionlimit(150)
341 360 def test_find_recursion(self):
342 361 captured = []
343 362 def capture_exc(*args, **kwargs):
344 363 captured.append(sys.exc_info())
345 364 with mock.patch.object(ip, 'showtraceback', capture_exc):
346 365 ip.run_cell("r3o2()")
347 366
348 367 self.assertEqual(len(captured), 1)
349 368 etype, evalue, tb = captured[0]
350 369 self.assertIn("recursion", str(evalue))
351 370
352 371 records = ip.InteractiveTB.get_records(tb, 3, ip.InteractiveTB.tb_offset)
353 372 for r in records[:10]:
354 373 print(r[1:4])
355 374
356 375 # The outermost frames should be:
357 376 # 0: the 'cell' that was running when the exception came up
358 377 # 1: r3o2()
359 378 # 2: r3o1()
360 379 # 3: r3a()
361 380 # Then repeating r3b, r3c, r3a
362 381 last_unique, repeat_length = find_recursion(etype, evalue, records)
363 382 self.assertEqual(last_unique, 2)
364 383 self.assertEqual(repeat_length, 3)
365 384
366 385
367 386 #----------------------------------------------------------------------------
368 387
369 388 # module testing (minimal)
370 389 def test_handlers():
371 390 def spam(c, d_e):
372 391 (d, e) = d_e
373 392 x = c + d
374 393 y = c * d
375 394 foo(x, y)
376 395
377 396 def foo(a, b, bar=1):
378 397 eggs(a, b + bar)
379 398
380 399 def eggs(f, g, z=globals()):
381 400 h = f + g
382 401 i = f - g
383 402 return h / i
384 403
385 404 buff = io.StringIO()
386 405
387 406 buff.write('')
388 407 buff.write('*** Before ***')
389 408 try:
390 409 buff.write(spam(1, (2, 3)))
391 410 except:
392 411 traceback.print_exc(file=buff)
393 412
394 413 handler = ColorTB(ostream=buff)
395 414 buff.write('*** ColorTB ***')
396 415 try:
397 416 buff.write(spam(1, (2, 3)))
398 417 except:
399 418 handler(*sys.exc_info())
400 419 buff.write('')
401 420
402 421 handler = VerboseTB(ostream=buff)
403 422 buff.write('*** VerboseTB ***')
404 423 try:
405 424 buff.write(spam(1, (2, 3)))
406 425 except:
407 426 handler(*sys.exc_info())
408 427 buff.write('')
409 428
410 429 from IPython.testing.decorators import skipif
411 430
412 431 class TokenizeFailureTest(unittest.TestCase):
413 432 """Tests related to https://github.com/ipython/ipython/issues/6864."""
414 433
415 434 # that appear to test that we are handling an exception that can be thrown
416 435 # by the tokenizer due to a bug that seem to have been fixed in 3.8, though
417 436 # I'm unsure if other sequences can make it raise this error. Let's just
418 437 # skip in 3.8 for now
419 438 @skipif(sys.version_info > (3,8))
420 439 def testLogging(self):
421 440 message = "An unexpected error occurred while tokenizing input"
422 441 cell = 'raise ValueError("""a\nb""")'
423 442
424 443 stream = io.StringIO()
425 444 handler = logging.StreamHandler(stream)
426 445 logger = logging.getLogger()
427 446 loglevel = logger.level
428 447 logger.addHandler(handler)
429 448 self.addCleanup(lambda: logger.removeHandler(handler))
430 449 self.addCleanup(lambda: logger.setLevel(loglevel))
431 450
432 451 logger.setLevel(logging.INFO)
433 452 with tt.AssertNotPrints(message):
434 453 ip.run_cell(cell)
435 454 self.assertNotIn(message, stream.getvalue())
436 455
437 456 logger.setLevel(logging.DEBUG)
438 457 with tt.AssertNotPrints(message):
439 458 ip.run_cell(cell)
440 459 self.assertIn(message, stream.getvalue())
@@ -1,1473 +1,1502 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Verbose and colourful traceback formatting.
4 4
5 5 **ColorTB**
6 6
7 7 I've always found it a bit hard to visually parse tracebacks in Python. The
8 8 ColorTB class is a solution to that problem. It colors the different parts of a
9 9 traceback in a manner similar to what you would expect from a syntax-highlighting
10 10 text editor.
11 11
12 12 Installation instructions for ColorTB::
13 13
14 14 import sys,ultratb
15 15 sys.excepthook = ultratb.ColorTB()
16 16
17 17 **VerboseTB**
18 18
19 19 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
20 20 of useful info when a traceback occurs. Ping originally had it spit out HTML
21 21 and intended it for CGI programmers, but why should they have all the fun? I
22 22 altered it to spit out colored text to the terminal. It's a bit overwhelming,
23 23 but kind of neat, and maybe useful for long-running programs that you believe
24 24 are bug-free. If a crash *does* occur in that type of program you want details.
25 25 Give it a shot--you'll love it or you'll hate it.
26 26
27 27 .. note::
28 28
29 29 The Verbose mode prints the variables currently visible where the exception
30 30 happened (shortening their strings if too long). This can potentially be
31 31 very slow, if you happen to have a huge data structure whose string
32 32 representation is complex to compute. Your computer may appear to freeze for
33 33 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
34 34 with Ctrl-C (maybe hitting it more than once).
35 35
36 36 If you encounter this kind of situation often, you may want to use the
37 37 Verbose_novars mode instead of the regular Verbose, which avoids formatting
38 38 variables (but otherwise includes the information and context given by
39 39 Verbose).
40 40
41 41 .. note::
42 42
43 43 The verbose mode print all variables in the stack, which means it can
44 44 potentially leak sensitive information like access keys, or unencrypted
45 45 password.
46 46
47 47 Installation instructions for VerboseTB::
48 48
49 49 import sys,ultratb
50 50 sys.excepthook = ultratb.VerboseTB()
51 51
52 52 Note: Much of the code in this module was lifted verbatim from the standard
53 53 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
54 54
55 55 Color schemes
56 56 -------------
57 57
58 58 The colors are defined in the class TBTools through the use of the
59 59 ColorSchemeTable class. Currently the following exist:
60 60
61 61 - NoColor: allows all of this module to be used in any terminal (the color
62 62 escapes are just dummy blank strings).
63 63
64 64 - Linux: is meant to look good in a terminal like the Linux console (black
65 65 or very dark background).
66 66
67 67 - LightBG: similar to Linux but swaps dark/light colors to be more readable
68 68 in light background terminals.
69 69
70 70 - Neutral: a neutral color scheme that should be readable on both light and
71 71 dark background
72 72
73 73 You can implement other color schemes easily, the syntax is fairly
74 74 self-explanatory. Please send back new schemes you develop to the author for
75 75 possible inclusion in future releases.
76 76
77 77 Inheritance diagram:
78 78
79 79 .. inheritance-diagram:: IPython.core.ultratb
80 80 :parts: 3
81 81 """
82 82
83 83 #*****************************************************************************
84 84 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
85 85 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
86 86 #
87 87 # Distributed under the terms of the BSD License. The full license is in
88 88 # the file COPYING, distributed as part of this software.
89 89 #*****************************************************************************
90 90
91 91
92 92 import dis
93 93 import inspect
94 94 import keyword
95 95 import linecache
96 96 import os
97 97 import pydoc
98 98 import re
99 99 import sys
100 100 import time
101 101 import tokenize
102 102 import traceback
103 103
104 104 try: # Python 2
105 105 generate_tokens = tokenize.generate_tokens
106 106 except AttributeError: # Python 3
107 107 generate_tokens = tokenize.tokenize
108 108
109 109 # For purposes of monkeypatching inspect to fix a bug in it.
110 110 from inspect import getsourcefile, getfile, getmodule, \
111 111 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
112 112
113 113 # IPython's own modules
114 114 from IPython import get_ipython
115 115 from IPython.core import debugger
116 116 from IPython.core.display_trap import DisplayTrap
117 117 from IPython.core.excolors import exception_colors
118 118 from IPython.utils import PyColorize
119 119 from IPython.utils import path as util_path
120 120 from IPython.utils import py3compat
121 121 from IPython.utils.data import uniq_stable
122 122 from IPython.utils.terminal import get_terminal_size
123 123
124 124 from logging import info, error, debug
125 125
126 126 from importlib.util import source_from_cache
127 127
128 128 import IPython.utils.colorable as colorable
129 129
130 130 # Globals
131 131 # amount of space to put line numbers before verbose tracebacks
132 132 INDENT_SIZE = 8
133 133
134 134 # Default color scheme. This is used, for example, by the traceback
135 135 # formatter. When running in an actual IPython instance, the user's rc.colors
136 136 # value is used, but having a module global makes this functionality available
137 137 # to users of ultratb who are NOT running inside ipython.
138 138 DEFAULT_SCHEME = 'NoColor'
139 139
140 140
141 141 # Number of frame above which we are likely to have a recursion and will
142 142 # **attempt** to detect it. Made modifiable mostly to speedup test suite
143 143 # as detecting recursion is one of our slowest test
144 144 _FRAME_RECURSION_LIMIT = 500
145 145
146 146 # ---------------------------------------------------------------------------
147 147 # Code begins
148 148
149 149 # Utility functions
150 150 def inspect_error():
151 151 """Print a message about internal inspect errors.
152 152
153 153 These are unfortunately quite common."""
154 154
155 155 error('Internal Python error in the inspect module.\n'
156 156 'Below is the traceback from this internal error.\n')
157 157
158 158
159 159 # This function is a monkeypatch we apply to the Python inspect module. We have
160 160 # now found when it's needed (see discussion on issue gh-1456), and we have a
161 161 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
162 162 # the monkeypatch is not applied. TK, Aug 2012.
163 163 def findsource(object):
164 164 """Return the entire source file and starting line number for an object.
165 165
166 166 The argument may be a module, class, method, function, traceback, frame,
167 167 or code object. The source code is returned as a list of all the lines
168 168 in the file and the line number indexes a line in that list. An IOError
169 169 is raised if the source code cannot be retrieved.
170 170
171 171 FIXED version with which we monkeypatch the stdlib to work around a bug."""
172 172
173 173 file = getsourcefile(object) or getfile(object)
174 174 # If the object is a frame, then trying to get the globals dict from its
175 175 # module won't work. Instead, the frame object itself has the globals
176 176 # dictionary.
177 177 globals_dict = None
178 178 if inspect.isframe(object):
179 179 # XXX: can this ever be false?
180 180 globals_dict = object.f_globals
181 181 else:
182 182 module = getmodule(object, file)
183 183 if module:
184 184 globals_dict = module.__dict__
185 185 lines = linecache.getlines(file, globals_dict)
186 186 if not lines:
187 187 raise IOError('could not get source code')
188 188
189 189 if ismodule(object):
190 190 return lines, 0
191 191
192 192 if isclass(object):
193 193 name = object.__name__
194 194 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
195 195 # make some effort to find the best matching class definition:
196 196 # use the one with the least indentation, which is the one
197 197 # that's most probably not inside a function definition.
198 198 candidates = []
199 199 for i, line in enumerate(lines):
200 200 match = pat.match(line)
201 201 if match:
202 202 # if it's at toplevel, it's already the best one
203 203 if line[0] == 'c':
204 204 return lines, i
205 205 # else add whitespace to candidate list
206 206 candidates.append((match.group(1), i))
207 207 if candidates:
208 208 # this will sort by whitespace, and by line number,
209 209 # less whitespace first
210 210 candidates.sort()
211 211 return lines, candidates[0][1]
212 212 else:
213 213 raise IOError('could not find class definition')
214 214
215 215 if ismethod(object):
216 216 object = object.__func__
217 217 if isfunction(object):
218 218 object = object.__code__
219 219 if istraceback(object):
220 220 object = object.tb_frame
221 221 if isframe(object):
222 222 object = object.f_code
223 223 if iscode(object):
224 224 if not hasattr(object, 'co_firstlineno'):
225 225 raise IOError('could not find function definition')
226 226 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
227 227 pmatch = pat.match
228 228 # fperez - fix: sometimes, co_firstlineno can give a number larger than
229 229 # the length of lines, which causes an error. Safeguard against that.
230 230 lnum = min(object.co_firstlineno, len(lines)) - 1
231 231 while lnum > 0:
232 232 if pmatch(lines[lnum]):
233 233 break
234 234 lnum -= 1
235 235
236 236 return lines, lnum
237 237 raise IOError('could not find code object')
238 238
239 239
240 240 # This is a patched version of inspect.getargs that applies the (unmerged)
241 241 # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes
242 242 # https://github.com/ipython/ipython/issues/8205 and
243 243 # https://github.com/ipython/ipython/issues/8293
244 244 def getargs(co):
245 245 """Get information about the arguments accepted by a code object.
246 246
247 247 Three things are returned: (args, varargs, varkw), where 'args' is
248 248 a list of argument names (possibly containing nested lists), and
249 249 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
250 250 if not iscode(co):
251 251 raise TypeError('{!r} is not a code object'.format(co))
252 252
253 253 nargs = co.co_argcount
254 254 names = co.co_varnames
255 255 args = list(names[:nargs])
256 256 step = 0
257 257
258 258 # The following acrobatics are for anonymous (tuple) arguments.
259 259 for i in range(nargs):
260 260 if args[i][:1] in ('', '.'):
261 261 stack, remain, count = [], [], []
262 262 while step < len(co.co_code):
263 263 op = ord(co.co_code[step])
264 264 step = step + 1
265 265 if op >= dis.HAVE_ARGUMENT:
266 266 opname = dis.opname[op]
267 267 value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
268 268 step = step + 2
269 269 if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
270 270 remain.append(value)
271 271 count.append(value)
272 272 elif opname in ('STORE_FAST', 'STORE_DEREF'):
273 273 if op in dis.haslocal:
274 274 stack.append(co.co_varnames[value])
275 275 elif op in dis.hasfree:
276 276 stack.append((co.co_cellvars + co.co_freevars)[value])
277 277 # Special case for sublists of length 1: def foo((bar))
278 278 # doesn't generate the UNPACK_TUPLE bytecode, so if
279 279 # `remain` is empty here, we have such a sublist.
280 280 if not remain:
281 281 stack[0] = [stack[0]]
282 282 break
283 283 else:
284 284 remain[-1] = remain[-1] - 1
285 285 while remain[-1] == 0:
286 286 remain.pop()
287 287 size = count.pop()
288 288 stack[-size:] = [stack[-size:]]
289 289 if not remain:
290 290 break
291 291 remain[-1] = remain[-1] - 1
292 292 if not remain:
293 293 break
294 294 args[i] = stack[0]
295 295
296 296 varargs = None
297 297 if co.co_flags & inspect.CO_VARARGS:
298 298 varargs = co.co_varnames[nargs]
299 299 nargs = nargs + 1
300 300 varkw = None
301 301 if co.co_flags & inspect.CO_VARKEYWORDS:
302 302 varkw = co.co_varnames[nargs]
303 303 return inspect.Arguments(args, varargs, varkw)
304 304
305 305
306 306 # Monkeypatch inspect to apply our bugfix.
307 307 def with_patch_inspect(f):
308 308 """
309 309 Deprecated since IPython 6.0
310 310 decorator for monkeypatching inspect.findsource
311 311 """
312 312
313 313 def wrapped(*args, **kwargs):
314 314 save_findsource = inspect.findsource
315 315 save_getargs = inspect.getargs
316 316 inspect.findsource = findsource
317 317 inspect.getargs = getargs
318 318 try:
319 319 return f(*args, **kwargs)
320 320 finally:
321 321 inspect.findsource = save_findsource
322 322 inspect.getargs = save_getargs
323 323
324 324 return wrapped
325 325
326 326
327 327 def fix_frame_records_filenames(records):
328 328 """Try to fix the filenames in each record from inspect.getinnerframes().
329 329
330 330 Particularly, modules loaded from within zip files have useless filenames
331 331 attached to their code object, and inspect.getinnerframes() just uses it.
332 332 """
333 333 fixed_records = []
334 334 for frame, filename, line_no, func_name, lines, index in records:
335 335 # Look inside the frame's globals dictionary for __file__,
336 336 # which should be better. However, keep Cython filenames since
337 337 # we prefer the source filenames over the compiled .so file.
338 338 if not filename.endswith(('.pyx', '.pxd', '.pxi')):
339 339 better_fn = frame.f_globals.get('__file__', None)
340 340 if isinstance(better_fn, str):
341 341 # Check the type just in case someone did something weird with
342 342 # __file__. It might also be None if the error occurred during
343 343 # import.
344 344 filename = better_fn
345 345 fixed_records.append((frame, filename, line_no, func_name, lines, index))
346 346 return fixed_records
347 347
348 348
349 349 @with_patch_inspect
350 350 def _fixed_getinnerframes(etb, context=1, tb_offset=0):
351 351 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
352 352
353 353 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
354 354 # If the error is at the console, don't build any context, since it would
355 355 # otherwise produce 5 blank lines printed out (there is no file at the
356 356 # console)
357 357 rec_check = records[tb_offset:]
358 358 try:
359 359 rname = rec_check[0][1]
360 360 if rname == '<ipython console>' or rname.endswith('<string>'):
361 361 return rec_check
362 362 except IndexError:
363 363 pass
364 364
365 365 aux = traceback.extract_tb(etb)
366 366 assert len(records) == len(aux)
367 367 for i, (file, lnum, _, _) in enumerate(aux):
368 368 maybeStart = lnum - 1 - context // 2
369 369 start = max(maybeStart, 0)
370 370 end = start + context
371 371 lines = linecache.getlines(file)[start:end]
372 372 buf = list(records[i])
373 373 buf[LNUM_POS] = lnum
374 374 buf[INDEX_POS] = lnum - 1 - start
375 375 buf[LINES_POS] = lines
376 376 records[i] = tuple(buf)
377 377 return records[tb_offset:]
378 378
379 379 # Helper function -- largely belongs to VerboseTB, but we need the same
380 380 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
381 381 # can be recognized properly by ipython.el's py-traceback-line-re
382 382 # (SyntaxErrors have to be treated specially because they have no traceback)
383 383
384 384
385 385 def _format_traceback_lines(lnum, index, lines, Colors, lvals, _line_format):
386 386 """
387 387 Format tracebacks lines with pointing arrow, leading numbers...
388 388
389 389 Parameters
390 390 ==========
391 391
392 392 lnum: int
393 393 index: int
394 394 lines: list[string]
395 395 Colors:
396 396 ColorScheme used.
397 397 lvals: bytes
398 398 Values of local variables, already colored, to inject just after the error line.
399 399 _line_format: f (str) -> (str, bool)
400 400 return (colorized version of str, failure to do so)
401 401 """
402 402 numbers_width = INDENT_SIZE - 1
403 403 res = []
404 404
405 405 for i,line in enumerate(lines, lnum-index):
406 406 line = py3compat.cast_unicode(line)
407 407
408 408 new_line, err = _line_format(line, 'str')
409 409 if not err:
410 410 line = new_line
411 411
412 412 if i == lnum:
413 413 # This is the line with the error
414 414 pad = numbers_width - len(str(i))
415 415 num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
416 416 line = '%s%s%s %s%s' % (Colors.linenoEm, num,
417 417 Colors.line, line, Colors.Normal)
418 418 else:
419 419 num = '%*s' % (numbers_width, i)
420 420 line = '%s%s%s %s' % (Colors.lineno, num,
421 421 Colors.Normal, line)
422 422
423 423 res.append(line)
424 424 if lvals and i == lnum:
425 425 res.append(lvals + '\n')
426 426 return res
427 427
428 428 def is_recursion_error(etype, value, records):
429 429 try:
430 430 # RecursionError is new in Python 3.5
431 431 recursion_error_type = RecursionError
432 432 except NameError:
433 433 recursion_error_type = RuntimeError
434 434
435 435 # The default recursion limit is 1000, but some of that will be taken up
436 436 # by stack frames in IPython itself. >500 frames probably indicates
437 437 # a recursion error.
438 438 return (etype is recursion_error_type) \
439 439 and "recursion" in str(value).lower() \
440 440 and len(records) > _FRAME_RECURSION_LIMIT
441 441
442 442 def find_recursion(etype, value, records):
443 443 """Identify the repeating stack frames from a RecursionError traceback
444 444
445 445 'records' is a list as returned by VerboseTB.get_records()
446 446
447 447 Returns (last_unique, repeat_length)
448 448 """
449 449 # This involves a bit of guesswork - we want to show enough of the traceback
450 450 # to indicate where the recursion is occurring. We guess that the innermost
451 451 # quarter of the traceback (250 frames by default) is repeats, and find the
452 452 # first frame (from in to out) that looks different.
453 453 if not is_recursion_error(etype, value, records):
454 454 return len(records), 0
455 455
456 456 # Select filename, lineno, func_name to track frames with
457 457 records = [r[1:4] for r in records]
458 458 inner_frames = records[-(len(records)//4):]
459 459 frames_repeated = set(inner_frames)
460 460
461 461 last_seen_at = {}
462 462 longest_repeat = 0
463 463 i = len(records)
464 464 for frame in reversed(records):
465 465 i -= 1
466 466 if frame not in frames_repeated:
467 467 last_unique = i
468 468 break
469 469
470 470 if frame in last_seen_at:
471 471 distance = last_seen_at[frame] - i
472 472 longest_repeat = max(longest_repeat, distance)
473 473
474 474 last_seen_at[frame] = i
475 475 else:
476 476 last_unique = 0 # The whole traceback was recursion
477 477
478 478 return last_unique, longest_repeat
479 479
480 480 #---------------------------------------------------------------------------
481 481 # Module classes
482 482 class TBTools(colorable.Colorable):
483 483 """Basic tools used by all traceback printer classes."""
484 484
485 485 # Number of frames to skip when reporting tracebacks
486 486 tb_offset = 0
487 487
488 488 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
489 489 # Whether to call the interactive pdb debugger after printing
490 490 # tracebacks or not
491 491 super(TBTools, self).__init__(parent=parent, config=config)
492 492 self.call_pdb = call_pdb
493 493
494 494 # Output stream to write to. Note that we store the original value in
495 495 # a private attribute and then make the public ostream a property, so
496 496 # that we can delay accessing sys.stdout until runtime. The way
497 497 # things are written now, the sys.stdout object is dynamically managed
498 498 # so a reference to it should NEVER be stored statically. This
499 499 # property approach confines this detail to a single location, and all
500 500 # subclasses can simply access self.ostream for writing.
501 501 self._ostream = ostream
502 502
503 503 # Create color table
504 504 self.color_scheme_table = exception_colors()
505 505
506 506 self.set_colors(color_scheme)
507 507 self.old_scheme = color_scheme # save initial value for toggles
508 508
509 509 if call_pdb:
510 510 self.pdb = debugger.Pdb()
511 511 else:
512 512 self.pdb = None
513 513
514 514 def _get_ostream(self):
515 515 """Output stream that exceptions are written to.
516 516
517 517 Valid values are:
518 518
519 519 - None: the default, which means that IPython will dynamically resolve
520 520 to sys.stdout. This ensures compatibility with most tools, including
521 521 Windows (where plain stdout doesn't recognize ANSI escapes).
522 522
523 523 - Any object with 'write' and 'flush' attributes.
524 524 """
525 525 return sys.stdout if self._ostream is None else self._ostream
526 526
527 527 def _set_ostream(self, val):
528 528 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
529 529 self._ostream = val
530 530
531 531 ostream = property(_get_ostream, _set_ostream)
532 532
533 def get_parts_of_chained_exception(self, evalue):
534 def get_chained_exception(exception_value):
535 cause = getattr(exception_value, '__cause__', None)
536 if cause:
537 return cause
538 if getattr(exception_value, '__suppress_context__', False):
539 return None
540 return getattr(exception_value, '__context__', None)
541
542 chained_evalue = get_chained_exception(evalue)
543
544 if chained_evalue:
545 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
546
547 def prepare_chained_exception_message(self, cause):
548 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
549 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
550
551 if cause:
552 message = [[direct_cause]]
553 else:
554 message = [[exception_during_handling]]
555 return message
556
533 557 def set_colors(self, *args, **kw):
534 558 """Shorthand access to the color table scheme selector method."""
535 559
536 560 # Set own color table
537 561 self.color_scheme_table.set_active_scheme(*args, **kw)
538 562 # for convenience, set Colors to the active scheme
539 563 self.Colors = self.color_scheme_table.active_colors
540 564 # Also set colors of debugger
541 565 if hasattr(self, 'pdb') and self.pdb is not None:
542 566 self.pdb.set_colors(*args, **kw)
543 567
544 568 def color_toggle(self):
545 569 """Toggle between the currently active color scheme and NoColor."""
546 570
547 571 if self.color_scheme_table.active_scheme_name == 'NoColor':
548 572 self.color_scheme_table.set_active_scheme(self.old_scheme)
549 573 self.Colors = self.color_scheme_table.active_colors
550 574 else:
551 575 self.old_scheme = self.color_scheme_table.active_scheme_name
552 576 self.color_scheme_table.set_active_scheme('NoColor')
553 577 self.Colors = self.color_scheme_table.active_colors
554 578
555 579 def stb2text(self, stb):
556 580 """Convert a structured traceback (a list) to a string."""
557 581 return '\n'.join(stb)
558 582
559 583 def text(self, etype, value, tb, tb_offset=None, context=5):
560 584 """Return formatted traceback.
561 585
562 586 Subclasses may override this if they add extra arguments.
563 587 """
564 588 tb_list = self.structured_traceback(etype, value, tb,
565 589 tb_offset, context)
566 590 return self.stb2text(tb_list)
567 591
568 592 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
569 593 context=5, mode=None):
570 594 """Return a list of traceback frames.
571 595
572 596 Must be implemented by each class.
573 597 """
574 598 raise NotImplementedError()
575 599
576 600
577 601 #---------------------------------------------------------------------------
578 602 class ListTB(TBTools):
579 603 """Print traceback information from a traceback list, with optional color.
580 604
581 605 Calling requires 3 arguments: (etype, evalue, elist)
582 606 as would be obtained by::
583 607
584 608 etype, evalue, tb = sys.exc_info()
585 609 if tb:
586 610 elist = traceback.extract_tb(tb)
587 611 else:
588 612 elist = None
589 613
590 614 It can thus be used by programs which need to process the traceback before
591 615 printing (such as console replacements based on the code module from the
592 616 standard library).
593 617
594 618 Because they are meant to be called without a full traceback (only a
595 619 list), instances of this class can't call the interactive pdb debugger."""
596 620
597 621 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
598 622 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
599 623 ostream=ostream, parent=parent,config=config)
600 624
601 625 def __call__(self, etype, value, elist):
602 626 self.ostream.flush()
603 627 self.ostream.write(self.text(etype, value, elist))
604 628 self.ostream.write('\n')
605 629
606 def structured_traceback(self, etype, value, elist, tb_offset=None,
630 def structured_traceback(self, etype, evalue, etb=None, tb_offset=None,
607 631 context=5):
608 632 """Return a color formatted string with the traceback info.
609 633
610 634 Parameters
611 635 ----------
612 636 etype : exception type
613 637 Type of the exception raised.
614 638
615 value : object
639 evalue : object
616 640 Data stored in the exception
617 641
618 elist : list
619 List of frames, see class docstring for details.
642 etb : object
643 If list: List of frames, see class docstring for details.
644 If Traceback: Traceback of the exception.
620 645
621 646 tb_offset : int, optional
622 647 Number of frames in the traceback to skip. If not given, the
623 instance value is used (set in constructor).
648 instance evalue is used (set in constructor).
624 649
625 650 context : int, optional
626 651 Number of lines of context information to print.
627 652
628 653 Returns
629 654 -------
630 655 String with formatted exception.
631 656 """
657 # This is a workaround to get chained_exc_ids in recursive calls
658 # etb should not be a tuple if structured_traceback is not recursive
659 if isinstance(etb, tuple):
660 etb, chained_exc_ids = etb
661 else:
662 chained_exc_ids = set()
663
664 if isinstance(etb, list):
665 elist = etb
666 elif etb is not None:
667 elist = self._extract_tb(etb)
668 else:
669 elist = []
632 670 tb_offset = self.tb_offset if tb_offset is None else tb_offset
633 671 Colors = self.Colors
634 672 out_list = []
635 673 if elist:
636 674
637 675 if tb_offset and len(elist) > tb_offset:
638 676 elist = elist[tb_offset:]
639 677
640 678 out_list.append('Traceback %s(most recent call last)%s:' %
641 679 (Colors.normalEm, Colors.Normal) + '\n')
642 680 out_list.extend(self._format_list(elist))
643 681 # The exception info should be a single entry in the list.
644 lines = ''.join(self._format_exception_only(etype, value))
682 lines = ''.join(self._format_exception_only(etype, evalue))
645 683 out_list.append(lines)
646 684
685 exception = self.get_parts_of_chained_exception(evalue)
686
687 if exception and not id(exception[1]) in chained_exc_ids:
688 chained_exception_message = self.prepare_chained_exception_message(
689 evalue.__cause__)[0]
690 etype, evalue, etb = exception
691 # Trace exception to avoid infinite 'cause' loop
692 chained_exc_ids.add(id(exception[1]))
693 chained_exceptions_tb_offset = 0
694 out_list = (
695 self.structured_traceback(
696 etype, evalue, (etb, chained_exc_ids),
697 chained_exceptions_tb_offset, context)
698 + chained_exception_message
699 + out_list)
700
647 701 return out_list
648 702
649 703 def _format_list(self, extracted_list):
650 704 """Format a list of traceback entry tuples for printing.
651 705
652 706 Given a list of tuples as returned by extract_tb() or
653 707 extract_stack(), return a list of strings ready for printing.
654 708 Each string in the resulting list corresponds to the item with the
655 709 same index in the argument list. Each string ends in a newline;
656 710 the strings may contain internal newlines as well, for those items
657 711 whose source text line is not None.
658 712
659 713 Lifted almost verbatim from traceback.py
660 714 """
661 715
662 716 Colors = self.Colors
663 717 list = []
664 718 for filename, lineno, name, line in extracted_list[:-1]:
665 719 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
666 720 (Colors.filename, filename, Colors.Normal,
667 721 Colors.lineno, lineno, Colors.Normal,
668 722 Colors.name, name, Colors.Normal)
669 723 if line:
670 724 item += ' %s\n' % line.strip()
671 725 list.append(item)
672 726 # Emphasize the last entry
673 727 filename, lineno, name, line = extracted_list[-1]
674 728 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
675 729 (Colors.normalEm,
676 730 Colors.filenameEm, filename, Colors.normalEm,
677 731 Colors.linenoEm, lineno, Colors.normalEm,
678 732 Colors.nameEm, name, Colors.normalEm,
679 733 Colors.Normal)
680 734 if line:
681 735 item += '%s %s%s\n' % (Colors.line, line.strip(),
682 736 Colors.Normal)
683 737 list.append(item)
684 738 return list
685 739
686 740 def _format_exception_only(self, etype, value):
687 741 """Format the exception part of a traceback.
688 742
689 743 The arguments are the exception type and value such as given by
690 744 sys.exc_info()[:2]. The return value is a list of strings, each ending
691 745 in a newline. Normally, the list contains a single string; however,
692 746 for SyntaxError exceptions, it contains several lines that (when
693 747 printed) display detailed information about where the syntax error
694 748 occurred. The message indicating which exception occurred is the
695 749 always last string in the list.
696 750
697 751 Also lifted nearly verbatim from traceback.py
698 752 """
699 753 have_filedata = False
700 754 Colors = self.Colors
701 755 list = []
702 756 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
703 757 if value is None:
704 758 # Not sure if this can still happen in Python 2.6 and above
705 759 list.append(stype + '\n')
706 760 else:
707 761 if issubclass(etype, SyntaxError):
708 762 have_filedata = True
709 763 if not value.filename: value.filename = "<string>"
710 764 if value.lineno:
711 765 lineno = value.lineno
712 766 textline = linecache.getline(value.filename, value.lineno)
713 767 else:
714 768 lineno = 'unknown'
715 769 textline = ''
716 770 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
717 771 (Colors.normalEm,
718 772 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
719 773 Colors.linenoEm, lineno, Colors.Normal ))
720 774 if textline == '':
721 775 textline = py3compat.cast_unicode(value.text, "utf-8")
722 776
723 777 if textline is not None:
724 778 i = 0
725 779 while i < len(textline) and textline[i].isspace():
726 780 i += 1
727 781 list.append('%s %s%s\n' % (Colors.line,
728 782 textline.strip(),
729 783 Colors.Normal))
730 784 if value.offset is not None:
731 785 s = ' '
732 786 for c in textline[i:value.offset - 1]:
733 787 if c.isspace():
734 788 s += c
735 789 else:
736 790 s += ' '
737 791 list.append('%s%s^%s\n' % (Colors.caret, s,
738 792 Colors.Normal))
739 793
740 794 try:
741 795 s = value.msg
742 796 except Exception:
743 797 s = self._some_str(value)
744 798 if s:
745 799 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
746 800 Colors.Normal, s))
747 801 else:
748 802 list.append('%s\n' % stype)
749 803
750 804 # sync with user hooks
751 805 if have_filedata:
752 806 ipinst = get_ipython()
753 807 if ipinst is not None:
754 808 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
755 809
756 810 return list
757 811
758 812 def get_exception_only(self, etype, value):
759 813 """Only print the exception type and message, without a traceback.
760 814
761 815 Parameters
762 816 ----------
763 817 etype : exception type
764 818 value : exception value
765 819 """
766 return ListTB.structured_traceback(self, etype, value, [])
820 return ListTB.structured_traceback(self, etype, value)
767 821
768 822 def show_exception_only(self, etype, evalue):
769 823 """Only print the exception type and message, without a traceback.
770 824
771 825 Parameters
772 826 ----------
773 827 etype : exception type
774 828 value : exception value
775 829 """
776 830 # This method needs to use __call__ from *this* class, not the one from
777 831 # a subclass whose signature or behavior may be different
778 832 ostream = self.ostream
779 833 ostream.flush()
780 834 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
781 835 ostream.flush()
782 836
783 837 def _some_str(self, value):
784 838 # Lifted from traceback.py
785 839 try:
786 840 return py3compat.cast_unicode(str(value))
787 841 except:
788 842 return u'<unprintable %s object>' % type(value).__name__
789 843
790 844
791 845 #----------------------------------------------------------------------------
792 846 class VerboseTB(TBTools):
793 847 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
794 848 of HTML. Requires inspect and pydoc. Crazy, man.
795 849
796 850 Modified version which optionally strips the topmost entries from the
797 851 traceback, to be used with alternate interpreters (because their own code
798 852 would appear in the traceback)."""
799 853
800 854 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
801 855 tb_offset=0, long_header=False, include_vars=True,
802 856 check_cache=None, debugger_cls = None,
803 857 parent=None, config=None):
804 858 """Specify traceback offset, headers and color scheme.
805 859
806 860 Define how many frames to drop from the tracebacks. Calling it with
807 861 tb_offset=1 allows use of this handler in interpreters which will have
808 862 their own code at the top of the traceback (VerboseTB will first
809 863 remove that frame before printing the traceback info)."""
810 864 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
811 865 ostream=ostream, parent=parent, config=config)
812 866 self.tb_offset = tb_offset
813 867 self.long_header = long_header
814 868 self.include_vars = include_vars
815 869 # By default we use linecache.checkcache, but the user can provide a
816 870 # different check_cache implementation. This is used by the IPython
817 871 # kernel to provide tracebacks for interactive code that is cached,
818 872 # by a compiler instance that flushes the linecache but preserves its
819 873 # own code cache.
820 874 if check_cache is None:
821 875 check_cache = linecache.checkcache
822 876 self.check_cache = check_cache
823 877
824 878 self.debugger_cls = debugger_cls or debugger.Pdb
825 879
826 880 def format_records(self, records, last_unique, recursion_repeat):
827 881 """Format the stack frames of the traceback"""
828 882 frames = []
829 883 for r in records[:last_unique+recursion_repeat+1]:
830 884 #print '*** record:',file,lnum,func,lines,index # dbg
831 885 frames.append(self.format_record(*r))
832 886
833 887 if recursion_repeat:
834 888 frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat)
835 889 frames.append(self.format_record(*records[last_unique+recursion_repeat+1]))
836 890
837 891 return frames
838 892
839 893 def format_record(self, frame, file, lnum, func, lines, index):
840 894 """Format a single stack frame"""
841 895 Colors = self.Colors # just a shorthand + quicker name lookup
842 896 ColorsNormal = Colors.Normal # used a lot
843 897 col_scheme = self.color_scheme_table.active_scheme_name
844 898 indent = ' ' * INDENT_SIZE
845 899 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
846 900 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
847 901 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
848 902 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
849 903 ColorsNormal)
850 904 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
851 905 (Colors.vName, Colors.valEm, ColorsNormal)
852 906 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
853 907 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
854 908 Colors.vName, ColorsNormal)
855 909 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
856 910
857 911 if not file:
858 912 file = '?'
859 913 elif file.startswith(str("<")) and file.endswith(str(">")):
860 914 # Not a real filename, no problem...
861 915 pass
862 916 elif not os.path.isabs(file):
863 917 # Try to make the filename absolute by trying all
864 918 # sys.path entries (which is also what linecache does)
865 919 for dirname in sys.path:
866 920 try:
867 921 fullname = os.path.join(dirname, file)
868 922 if os.path.isfile(fullname):
869 923 file = os.path.abspath(fullname)
870 924 break
871 925 except Exception:
872 926 # Just in case that sys.path contains very
873 927 # strange entries...
874 928 pass
875 929
876 930 file = py3compat.cast_unicode(file, util_path.fs_encoding)
877 931 link = tpl_link % util_path.compress_user(file)
878 932 args, varargs, varkw, locals_ = inspect.getargvalues(frame)
879 933
880 934 if func == '?':
881 935 call = ''
882 936 elif func == '<module>':
883 937 call = tpl_call % (func, '')
884 938 else:
885 939 # Decide whether to include variable details or not
886 940 var_repr = eqrepr if self.include_vars else nullrepr
887 941 try:
888 942 call = tpl_call % (func, inspect.formatargvalues(args,
889 943 varargs, varkw,
890 944 locals_, formatvalue=var_repr))
891 945 except KeyError:
892 946 # This happens in situations like errors inside generator
893 947 # expressions, where local variables are listed in the
894 948 # line, but can't be extracted from the frame. I'm not
895 949 # 100% sure this isn't actually a bug in inspect itself,
896 950 # but since there's no info for us to compute with, the
897 951 # best we can do is report the failure and move on. Here
898 952 # we must *not* call any traceback construction again,
899 953 # because that would mess up use of %debug later on. So we
900 954 # simply report the failure and move on. The only
901 955 # limitation will be that this frame won't have locals
902 956 # listed in the call signature. Quite subtle problem...
903 957 # I can't think of a good way to validate this in a unit
904 958 # test, but running a script consisting of:
905 959 # dict( (k,v.strip()) for (k,v) in range(10) )
906 960 # will illustrate the error, if this exception catch is
907 961 # disabled.
908 962 call = tpl_call_fail % func
909 963
910 964 # Don't attempt to tokenize binary files.
911 965 if file.endswith(('.so', '.pyd', '.dll')):
912 966 return '%s %s\n' % (link, call)
913 967
914 968 elif file.endswith(('.pyc', '.pyo')):
915 969 # Look up the corresponding source file.
916 970 try:
917 971 file = source_from_cache(file)
918 972 except ValueError:
919 973 # Failed to get the source file for some reason
920 974 # E.g. https://github.com/ipython/ipython/issues/9486
921 975 return '%s %s\n' % (link, call)
922 976
923 977 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
924 978 line = getline(file, lnum[0])
925 979 lnum[0] += 1
926 980 return line
927 981
928 982 # Build the list of names on this line of code where the exception
929 983 # occurred.
930 984 try:
931 985 names = []
932 986 name_cont = False
933 987
934 988 for token_type, token, start, end, line in generate_tokens(linereader):
935 989 # build composite names
936 990 if token_type == tokenize.NAME and token not in keyword.kwlist:
937 991 if name_cont:
938 992 # Continuation of a dotted name
939 993 try:
940 994 names[-1].append(token)
941 995 except IndexError:
942 996 names.append([token])
943 997 name_cont = False
944 998 else:
945 999 # Regular new names. We append everything, the caller
946 1000 # will be responsible for pruning the list later. It's
947 1001 # very tricky to try to prune as we go, b/c composite
948 1002 # names can fool us. The pruning at the end is easy
949 1003 # to do (or the caller can print a list with repeated
950 1004 # names if so desired.
951 1005 names.append([token])
952 1006 elif token == '.':
953 1007 name_cont = True
954 1008 elif token_type == tokenize.NEWLINE:
955 1009 break
956 1010
957 1011 except (IndexError, UnicodeDecodeError, SyntaxError):
958 1012 # signals exit of tokenizer
959 1013 # SyntaxError can occur if the file is not actually Python
960 1014 # - see gh-6300
961 1015 pass
962 1016 except tokenize.TokenError as msg:
963 1017 # Tokenizing may fail for various reasons, many of which are
964 1018 # harmless. (A good example is when the line in question is the
965 1019 # close of a triple-quoted string, cf gh-6864). We don't want to
966 1020 # show this to users, but want make it available for debugging
967 1021 # purposes.
968 1022 _m = ("An unexpected error occurred while tokenizing input\n"
969 1023 "The following traceback may be corrupted or invalid\n"
970 1024 "The error message is: %s\n" % msg)
971 1025 debug(_m)
972 1026
973 1027 # Join composite names (e.g. "dict.fromkeys")
974 1028 names = ['.'.join(n) for n in names]
975 1029 # prune names list of duplicates, but keep the right order
976 1030 unique_names = uniq_stable(names)
977 1031
978 1032 # Start loop over vars
979 1033 lvals = ''
980 1034 lvals_list = []
981 1035 if self.include_vars:
982 1036 for name_full in unique_names:
983 1037 name_base = name_full.split('.', 1)[0]
984 1038 if name_base in frame.f_code.co_varnames:
985 1039 if name_base in locals_:
986 1040 try:
987 1041 value = repr(eval(name_full, locals_))
988 1042 except:
989 1043 value = undefined
990 1044 else:
991 1045 value = undefined
992 1046 name = tpl_local_var % name_full
993 1047 else:
994 1048 if name_base in frame.f_globals:
995 1049 try:
996 1050 value = repr(eval(name_full, frame.f_globals))
997 1051 except:
998 1052 value = undefined
999 1053 else:
1000 1054 value = undefined
1001 1055 name = tpl_global_var % name_full
1002 1056 lvals_list.append(tpl_name_val % (name, value))
1003 1057 if lvals_list:
1004 1058 lvals = '%s%s' % (indent, em_normal.join(lvals_list))
1005 1059
1006 1060 level = '%s %s\n' % (link, call)
1007 1061
1008 1062 if index is None:
1009 1063 return level
1010 1064 else:
1011 1065 _line_format = PyColorize.Parser(style=col_scheme, parent=self).format2
1012 1066 return '%s%s' % (level, ''.join(
1013 1067 _format_traceback_lines(lnum, index, lines, Colors, lvals,
1014 1068 _line_format)))
1015 1069
1016 def prepare_chained_exception_message(self, cause):
1017 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
1018 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
1019
1020 if cause:
1021 message = [[direct_cause]]
1022 else:
1023 message = [[exception_during_handling]]
1024 return message
1025
1026 1070 def prepare_header(self, etype, long_version=False):
1027 1071 colors = self.Colors # just a shorthand + quicker name lookup
1028 1072 colorsnormal = colors.Normal # used a lot
1029 1073 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
1030 1074 width = min(75, get_terminal_size()[0])
1031 1075 if long_version:
1032 1076 # Header with the exception type, python version, and date
1033 1077 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
1034 1078 date = time.ctime(time.time())
1035 1079
1036 1080 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
1037 1081 exc, ' ' * (width - len(str(etype)) - len(pyver)),
1038 1082 pyver, date.rjust(width) )
1039 1083 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
1040 1084 "\ncalls leading up to the error, with the most recent (innermost) call last."
1041 1085 else:
1042 1086 # Simplified header
1043 1087 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
1044 1088 rjust(width - len(str(etype))) )
1045 1089
1046 1090 return head
1047 1091
1048 1092 def format_exception(self, etype, evalue):
1049 1093 colors = self.Colors # just a shorthand + quicker name lookup
1050 1094 colorsnormal = colors.Normal # used a lot
1051 1095 # Get (safely) a string form of the exception info
1052 1096 try:
1053 1097 etype_str, evalue_str = map(str, (etype, evalue))
1054 1098 except:
1055 1099 # User exception is improperly defined.
1056 1100 etype, evalue = str, sys.exc_info()[:2]
1057 1101 etype_str, evalue_str = map(str, (etype, evalue))
1058 1102 # ... and format it
1059 1103 return ['%s%s%s: %s' % (colors.excName, etype_str,
1060 1104 colorsnormal, py3compat.cast_unicode(evalue_str))]
1061 1105
1062 1106 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
1063 1107 """Formats the header, traceback and exception message for a single exception.
1064 1108
1065 1109 This may be called multiple times by Python 3 exception chaining
1066 1110 (PEP 3134).
1067 1111 """
1068 1112 # some locals
1069 1113 orig_etype = etype
1070 1114 try:
1071 1115 etype = etype.__name__
1072 1116 except AttributeError:
1073 1117 pass
1074 1118
1075 1119 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1076 1120 head = self.prepare_header(etype, self.long_header)
1077 1121 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
1078 1122
1079 1123 if records is None:
1080 1124 return ""
1081 1125
1082 1126 last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
1083 1127
1084 1128 frames = self.format_records(records, last_unique, recursion_repeat)
1085 1129
1086 1130 formatted_exception = self.format_exception(etype, evalue)
1087 1131 if records:
1088 1132 filepath, lnum = records[-1][1:3]
1089 1133 filepath = os.path.abspath(filepath)
1090 1134 ipinst = get_ipython()
1091 1135 if ipinst is not None:
1092 1136 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
1093 1137
1094 1138 return [[head] + frames + [''.join(formatted_exception[0])]]
1095 1139
1096 1140 def get_records(self, etb, number_of_lines_of_context, tb_offset):
1097 1141 try:
1098 1142 # Try the default getinnerframes and Alex's: Alex's fixes some
1099 1143 # problems, but it generates empty tracebacks for console errors
1100 1144 # (5 blanks lines) where none should be returned.
1101 1145 return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
1102 1146 except UnicodeDecodeError:
1103 1147 # This can occur if a file's encoding magic comment is wrong.
1104 1148 # I can't see a way to recover without duplicating a bunch of code
1105 1149 # from the stdlib traceback module. --TK
1106 1150 error('\nUnicodeDecodeError while processing traceback.\n')
1107 1151 return None
1108 1152 except:
1109 1153 # FIXME: I've been getting many crash reports from python 2.3
1110 1154 # users, traceable to inspect.py. If I can find a small test-case
1111 1155 # to reproduce this, I should either write a better workaround or
1112 1156 # file a bug report against inspect (if that's the real problem).
1113 1157 # So far, I haven't been able to find an isolated example to
1114 1158 # reproduce the problem.
1115 1159 inspect_error()
1116 1160 traceback.print_exc(file=self.ostream)
1117 1161 info('\nUnfortunately, your original traceback can not be constructed.\n')
1118 1162 return None
1119 1163
1120 def get_parts_of_chained_exception(self, evalue):
1121 def get_chained_exception(exception_value):
1122 cause = getattr(exception_value, '__cause__', None)
1123 if cause:
1124 return cause
1125 if getattr(exception_value, '__suppress_context__', False):
1126 return None
1127 return getattr(exception_value, '__context__', None)
1128
1129 chained_evalue = get_chained_exception(evalue)
1130
1131 if chained_evalue:
1132 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
1133
1134 1164 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
1135 1165 number_of_lines_of_context=5):
1136 1166 """Return a nice text document describing the traceback."""
1137 1167
1138 1168 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
1139 1169 tb_offset)
1140 1170
1141 1171 colors = self.Colors # just a shorthand + quicker name lookup
1142 1172 colorsnormal = colors.Normal # used a lot
1143 1173 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
1144 1174 structured_traceback_parts = [head]
1145 1175 chained_exceptions_tb_offset = 0
1146 1176 lines_of_context = 3
1147 1177 formatted_exceptions = formatted_exception
1148 1178 exception = self.get_parts_of_chained_exception(evalue)
1149 1179 if exception:
1150 1180 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1151 1181 etype, evalue, etb = exception
1152 1182 else:
1153 1183 evalue = None
1154 1184 chained_exc_ids = set()
1155 1185 while evalue:
1156 1186 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
1157 1187 chained_exceptions_tb_offset)
1158 1188 exception = self.get_parts_of_chained_exception(evalue)
1159 1189
1160 1190 if exception and not id(exception[1]) in chained_exc_ids:
1161 1191 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
1162 1192 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1163 1193 etype, evalue, etb = exception
1164 1194 else:
1165 1195 evalue = None
1166 1196
1167 1197 # we want to see exceptions in a reversed order:
1168 1198 # the first exception should be on top
1169 1199 for formatted_exception in reversed(formatted_exceptions):
1170 1200 structured_traceback_parts += formatted_exception
1171 1201
1172 1202 return structured_traceback_parts
1173 1203
1174 1204 def debugger(self, force=False):
1175 1205 """Call up the pdb debugger if desired, always clean up the tb
1176 1206 reference.
1177 1207
1178 1208 Keywords:
1179 1209
1180 1210 - force(False): by default, this routine checks the instance call_pdb
1181 1211 flag and does not actually invoke the debugger if the flag is false.
1182 1212 The 'force' option forces the debugger to activate even if the flag
1183 1213 is false.
1184 1214
1185 1215 If the call_pdb flag is set, the pdb interactive debugger is
1186 1216 invoked. In all cases, the self.tb reference to the current traceback
1187 1217 is deleted to prevent lingering references which hamper memory
1188 1218 management.
1189 1219
1190 1220 Note that each call to pdb() does an 'import readline', so if your app
1191 1221 requires a special setup for the readline completers, you'll have to
1192 1222 fix that by hand after invoking the exception handler."""
1193 1223
1194 1224 if force or self.call_pdb:
1195 1225 if self.pdb is None:
1196 1226 self.pdb = self.debugger_cls()
1197 1227 # the system displayhook may have changed, restore the original
1198 1228 # for pdb
1199 1229 display_trap = DisplayTrap(hook=sys.__displayhook__)
1200 1230 with display_trap:
1201 1231 self.pdb.reset()
1202 1232 # Find the right frame so we don't pop up inside ipython itself
1203 1233 if hasattr(self, 'tb') and self.tb is not None:
1204 1234 etb = self.tb
1205 1235 else:
1206 1236 etb = self.tb = sys.last_traceback
1207 1237 while self.tb is not None and self.tb.tb_next is not None:
1208 1238 self.tb = self.tb.tb_next
1209 1239 if etb and etb.tb_next:
1210 1240 etb = etb.tb_next
1211 1241 self.pdb.botframe = etb.tb_frame
1212 1242 self.pdb.interaction(None, etb)
1213 1243
1214 1244 if hasattr(self, 'tb'):
1215 1245 del self.tb
1216 1246
1217 1247 def handler(self, info=None):
1218 1248 (etype, evalue, etb) = info or sys.exc_info()
1219 1249 self.tb = etb
1220 1250 ostream = self.ostream
1221 1251 ostream.flush()
1222 1252 ostream.write(self.text(etype, evalue, etb))
1223 1253 ostream.write('\n')
1224 1254 ostream.flush()
1225 1255
1226 1256 # Changed so an instance can just be called as VerboseTB_inst() and print
1227 1257 # out the right info on its own.
1228 1258 def __call__(self, etype=None, evalue=None, etb=None):
1229 1259 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1230 1260 if etb is None:
1231 1261 self.handler()
1232 1262 else:
1233 1263 self.handler((etype, evalue, etb))
1234 1264 try:
1235 1265 self.debugger()
1236 1266 except KeyboardInterrupt:
1237 1267 print("\nKeyboardInterrupt")
1238 1268
1239 1269
1240 1270 #----------------------------------------------------------------------------
1241 1271 class FormattedTB(VerboseTB, ListTB):
1242 1272 """Subclass ListTB but allow calling with a traceback.
1243 1273
1244 1274 It can thus be used as a sys.excepthook for Python > 2.1.
1245 1275
1246 1276 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1247 1277
1248 1278 Allows a tb_offset to be specified. This is useful for situations where
1249 1279 one needs to remove a number of topmost frames from the traceback (such as
1250 1280 occurs with python programs that themselves execute other python code,
1251 1281 like Python shells). """
1252 1282
1253 1283 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1254 1284 ostream=None,
1255 1285 tb_offset=0, long_header=False, include_vars=False,
1256 1286 check_cache=None, debugger_cls=None,
1257 1287 parent=None, config=None):
1258 1288
1259 1289 # NEVER change the order of this list. Put new modes at the end:
1260 1290 self.valid_modes = ['Plain', 'Context', 'Verbose', 'Minimal']
1261 1291 self.verbose_modes = self.valid_modes[1:3]
1262 1292
1263 1293 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1264 1294 ostream=ostream, tb_offset=tb_offset,
1265 1295 long_header=long_header, include_vars=include_vars,
1266 1296 check_cache=check_cache, debugger_cls=debugger_cls,
1267 1297 parent=parent, config=config)
1268 1298
1269 1299 # Different types of tracebacks are joined with different separators to
1270 1300 # form a single string. They are taken from this dict
1271 1301 self._join_chars = dict(Plain='', Context='\n', Verbose='\n',
1272 1302 Minimal='')
1273 1303 # set_mode also sets the tb_join_char attribute
1274 1304 self.set_mode(mode)
1275 1305
1276 1306 def _extract_tb(self, tb):
1277 1307 if tb:
1278 1308 return traceback.extract_tb(tb)
1279 1309 else:
1280 1310 return None
1281 1311
1282 1312 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
1283 1313 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1284 1314 mode = self.mode
1285 1315 if mode in self.verbose_modes:
1286 1316 # Verbose modes need a full traceback
1287 1317 return VerboseTB.structured_traceback(
1288 1318 self, etype, value, tb, tb_offset, number_of_lines_of_context
1289 1319 )
1290 1320 elif mode == 'Minimal':
1291 1321 return ListTB.get_exception_only(self, etype, value)
1292 1322 else:
1293 1323 # We must check the source cache because otherwise we can print
1294 1324 # out-of-date source code.
1295 1325 self.check_cache()
1296 1326 # Now we can extract and format the exception
1297 elist = self._extract_tb(tb)
1298 1327 return ListTB.structured_traceback(
1299 self, etype, value, elist, tb_offset, number_of_lines_of_context
1328 self, etype, value, tb, tb_offset, number_of_lines_of_context
1300 1329 )
1301 1330
1302 1331 def stb2text(self, stb):
1303 1332 """Convert a structured traceback (a list) to a string."""
1304 1333 return self.tb_join_char.join(stb)
1305 1334
1306 1335
1307 1336 def set_mode(self, mode=None):
1308 1337 """Switch to the desired mode.
1309 1338
1310 1339 If mode is not specified, cycles through the available modes."""
1311 1340
1312 1341 if not mode:
1313 1342 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
1314 1343 len(self.valid_modes)
1315 1344 self.mode = self.valid_modes[new_idx]
1316 1345 elif mode not in self.valid_modes:
1317 1346 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
1318 1347 'Valid modes: ' + str(self.valid_modes))
1319 1348 else:
1320 1349 self.mode = mode
1321 1350 # include variable details only in 'Verbose' mode
1322 1351 self.include_vars = (self.mode == self.valid_modes[2])
1323 1352 # Set the join character for generating text tracebacks
1324 1353 self.tb_join_char = self._join_chars[self.mode]
1325 1354
1326 1355 # some convenient shortcuts
1327 1356 def plain(self):
1328 1357 self.set_mode(self.valid_modes[0])
1329 1358
1330 1359 def context(self):
1331 1360 self.set_mode(self.valid_modes[1])
1332 1361
1333 1362 def verbose(self):
1334 1363 self.set_mode(self.valid_modes[2])
1335 1364
1336 1365 def minimal(self):
1337 1366 self.set_mode(self.valid_modes[3])
1338 1367
1339 1368
1340 1369 #----------------------------------------------------------------------------
1341 1370 class AutoFormattedTB(FormattedTB):
1342 1371 """A traceback printer which can be called on the fly.
1343 1372
1344 1373 It will find out about exceptions by itself.
1345 1374
1346 1375 A brief example::
1347 1376
1348 1377 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1349 1378 try:
1350 1379 ...
1351 1380 except:
1352 1381 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1353 1382 """
1354 1383
1355 1384 def __call__(self, etype=None, evalue=None, etb=None,
1356 1385 out=None, tb_offset=None):
1357 1386 """Print out a formatted exception traceback.
1358 1387
1359 1388 Optional arguments:
1360 1389 - out: an open file-like object to direct output to.
1361 1390
1362 1391 - tb_offset: the number of frames to skip over in the stack, on a
1363 1392 per-call basis (this overrides temporarily the instance's tb_offset
1364 1393 given at initialization time. """
1365 1394
1366 1395 if out is None:
1367 1396 out = self.ostream
1368 1397 out.flush()
1369 1398 out.write(self.text(etype, evalue, etb, tb_offset))
1370 1399 out.write('\n')
1371 1400 out.flush()
1372 1401 # FIXME: we should remove the auto pdb behavior from here and leave
1373 1402 # that to the clients.
1374 1403 try:
1375 1404 self.debugger()
1376 1405 except KeyboardInterrupt:
1377 1406 print("\nKeyboardInterrupt")
1378 1407
1379 1408 def structured_traceback(self, etype=None, value=None, tb=None,
1380 1409 tb_offset=None, number_of_lines_of_context=5):
1381 1410 if etype is None:
1382 1411 etype, value, tb = sys.exc_info()
1383 1412 self.tb = tb
1384 1413 return FormattedTB.structured_traceback(
1385 1414 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1386 1415
1387 1416
1388 1417 #---------------------------------------------------------------------------
1389 1418
1390 1419 # A simple class to preserve Nathan's original functionality.
1391 1420 class ColorTB(FormattedTB):
1392 1421 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1393 1422
1394 1423 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1395 1424 FormattedTB.__init__(self, color_scheme=color_scheme,
1396 1425 call_pdb=call_pdb, **kwargs)
1397 1426
1398 1427
1399 1428 class SyntaxTB(ListTB):
1400 1429 """Extension which holds some state: the last exception value"""
1401 1430
1402 1431 def __init__(self, color_scheme='NoColor', parent=None, config=None):
1403 1432 ListTB.__init__(self, color_scheme, parent=parent, config=config)
1404 1433 self.last_syntax_error = None
1405 1434
1406 1435 def __call__(self, etype, value, elist):
1407 1436 self.last_syntax_error = value
1408 1437
1409 1438 ListTB.__call__(self, etype, value, elist)
1410 1439
1411 1440 def structured_traceback(self, etype, value, elist, tb_offset=None,
1412 1441 context=5):
1413 1442 # If the source file has been edited, the line in the syntax error can
1414 1443 # be wrong (retrieved from an outdated cache). This replaces it with
1415 1444 # the current value.
1416 1445 if isinstance(value, SyntaxError) \
1417 1446 and isinstance(value.filename, str) \
1418 1447 and isinstance(value.lineno, int):
1419 1448 linecache.checkcache(value.filename)
1420 1449 newtext = linecache.getline(value.filename, value.lineno)
1421 1450 if newtext:
1422 1451 value.text = newtext
1423 1452 self.last_syntax_error = value
1424 1453 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1425 1454 tb_offset=tb_offset, context=context)
1426 1455
1427 1456 def clear_err_state(self):
1428 1457 """Return the current error state and clear it"""
1429 1458 e = self.last_syntax_error
1430 1459 self.last_syntax_error = None
1431 1460 return e
1432 1461
1433 1462 def stb2text(self, stb):
1434 1463 """Convert a structured traceback (a list) to a string."""
1435 1464 return ''.join(stb)
1436 1465
1437 1466
1438 1467 # some internal-use functions
1439 1468 def text_repr(value):
1440 1469 """Hopefully pretty robust repr equivalent."""
1441 1470 # this is pretty horrible but should always return *something*
1442 1471 try:
1443 1472 return pydoc.text.repr(value)
1444 1473 except KeyboardInterrupt:
1445 1474 raise
1446 1475 except:
1447 1476 try:
1448 1477 return repr(value)
1449 1478 except KeyboardInterrupt:
1450 1479 raise
1451 1480 except:
1452 1481 try:
1453 1482 # all still in an except block so we catch
1454 1483 # getattr raising
1455 1484 name = getattr(value, '__name__', None)
1456 1485 if name:
1457 1486 # ick, recursion
1458 1487 return text_repr(name)
1459 1488 klass = getattr(value, '__class__', None)
1460 1489 if klass:
1461 1490 return '%s instance' % text_repr(klass)
1462 1491 except KeyboardInterrupt:
1463 1492 raise
1464 1493 except:
1465 1494 return 'UNRECOVERABLE REPR FAILURE'
1466 1495
1467 1496
1468 1497 def eqrepr(value, repr=text_repr):
1469 1498 return '=%s' % repr(value)
1470 1499
1471 1500
1472 1501 def nullrepr(value, repr=text_repr):
1473 1502 return ''
General Comments 0
You need to be logged in to leave comments. Login now