traceback.py 22.6 KB
Newer Older
1
"""Extract, format and print information about Python stack traces."""
2

3 4
import collections
import itertools
5 6 7
import linecache
import sys

8 9
__all__ = ['extract_stack', 'extract_tb', 'format_exception',
           'format_exception_only', 'format_list', 'format_stack',
10
           'format_tb', 'print_exc', 'format_exc', 'print_exception',
11 12 13
           'print_last', 'print_stack', 'print_tb', 'clear_frames',
           'FrameSummary', 'StackSummary', 'TracebackException',
           'walk_stack', 'walk_tb']
14

15 16 17
#
# Formatting and printing lists of traceback lines.
#
18 19

def print_list(extracted_list, file=None):
Tim Peters's avatar
Tim Peters committed
20 21
    """Print the list of tuples as returned by extract_tb() or
    extract_stack() as a formatted stack trace to the given file."""
22
    if file is None:
Tim Peters's avatar
Tim Peters committed
23
        file = sys.stderr
24
    for item in StackSummary.from_list(extracted_list).format():
25
        print(item, file=file, end="")
26 27

def format_list(extracted_list):
28 29 30
    """Format a list of traceback entry tuples for printing.

    Given a list of tuples as returned by extract_tb() or
Tim Peters's avatar
Tim Peters committed
31
    extract_stack(), return a list of strings ready for printing.
32 33 34 35 36
    Each string in the resulting list corresponds to the item with the
    same index in the argument list.  Each string ends in a newline;
    the strings may contain internal newlines as well, for those items
    whose source text line is not None.
    """
37
    return StackSummary.from_list(extracted_list).format()
38 39 40 41 42

#
# Printing and Extracting Tracebacks.
#

43
def print_tb(tb, limit=None, file=None):
Tim Peters's avatar
Tim Peters committed
44
    """Print up to 'limit' stack trace entries from the traceback 'tb'.
45 46 47 48 49 50

    If 'limit' is omitted or None, all entries are printed.  If 'file'
    is omitted or None, the output goes to sys.stderr; otherwise
    'file' should be an open file or file-like object with a write()
    method.
    """
51
    print_list(extract_tb(tb, limit=limit), file=file)
52

Georg Brandl's avatar
Georg Brandl committed
53
def format_tb(tb, limit=None):
54
    """A shorthand for 'format_list(extract_tb(tb, limit))'."""
55
    return extract_tb(tb, limit=limit).format()
56

Georg Brandl's avatar
Georg Brandl committed
57
def extract_tb(tb, limit=None):
58 59 60 61 62 63 64 65 66 67
    """Return list of up to limit pre-processed entries from traceback.

    This is useful for alternate formatting of stack traces.  If
    'limit' is omitted or None, all entries are extracted.  A
    pre-processed stack trace entry is a quadruple (filename, line
    number, function name, text) representing the information that is
    usually printed for a stack trace.  The text is a string with
    leading and trailing whitespace stripped; if the source is not
    available it is None.
    """
68
    return StackSummary.extract(walk_tb(tb), limit=limit)
69

70 71 72
#
# Exception formatting and output.
#
73

74 75
_cause_message = (
    "\nThe above exception was the direct cause "
76
    "of the following exception:\n\n")
77 78 79

_context_message = (
    "\nDuring handling of the above exception, "
80 81
    "another exception occurred:\n\n")

82 83

def print_exception(etype, value, tb, limit=None, file=None, chain=True):
84 85 86 87 88 89 90
    """Print exception up to 'limit' stack trace entries from 'tb' to 'file'.

    This differs from print_tb() in the following ways: (1) if
    traceback is not None, it prints a header "Traceback (most recent
    call last):"; (2) it prints the exception type and value after the
    stack trace; (3) if type is SyntaxError and value has the
    appropriate format, it prints the line where the syntax error
Tim Peters's avatar
Tim Peters committed
91
    occurred with a caret on the next line indicating the approximate
92 93
    position of the error.
    """
94 95 96
    # format_exception has ignored etype for some time, and code such as cgitb
    # passes in bogus values as a result. For compatibility with such code we
    # ignore it here (rather than in the new TracebackException API).
97
    if file is None:
Tim Peters's avatar
Tim Peters committed
98
        file = sys.stderr
99
    for line in TracebackException(
100
            type(value), value, tb, limit=limit).format(chain=chain):
101
        print(line, file=file, end="")
102

103

104
def format_exception(etype, value, tb, limit=None, chain=True):
105 106 107 108
    """Format a stack trace and the exception information.

    The arguments have the same meaning as the corresponding arguments
    to print_exception().  The return value is a list of strings, each
Tim Peters's avatar
Tim Peters committed
109 110
    ending in a newline and some containing internal newlines.  When
    these lines are concatenated and printed, exactly the same text is
111 112
    printed as does print_exception().
    """
113 114 115
    # format_exception has ignored etype for some time, and code such as cgitb
    # passes in bogus values as a result. For compatibility with such code we
    # ignore it here (rather than in the new TracebackException API).
116
    return list(TracebackException(
117
        type(value), value, tb, limit=limit).format(chain=chain))
118

119 120

def format_exception_only(etype, value):
121 122 123 124
    """Format the exception part of a traceback.

    The arguments are the exception type and value such as given by
    sys.last_type and sys.last_value. The return value is a list of
125 126 127 128 129 130 131 132 133 134
    strings, each ending in a newline.

    Normally, the list contains a single string; however, for
    SyntaxError exceptions, it contains several lines that (when
    printed) display detailed information about where the syntax
    error occurred.

    The message indicating which exception occurred is always the last
    string in the list.

135
    """
136 137 138
    return list(TracebackException(etype, value, None).format_exception_only())


139
# -- not official API but folk probably use these two functions.
140 141 142

def _format_final_exc_line(etype, value):
    valuestr = _some_str(value)
143
    if value == 'None' or value is None or not valuestr:
144
        line = "%s\n" % etype
Tim Peters's avatar
Tim Peters committed
145
    else:
146 147
        line = "%s: %s\n" % (etype, valuestr)
    return line
148

149
def _some_str(value):
Tim Peters's avatar
Tim Peters committed
150 151 152 153
    try:
        return str(value)
    except:
        return '<unprintable %s object>' % type(value).__name__
154

155 156
# --

157
def print_exc(limit=None, file=None, chain=True):
158
    """Shorthand for 'print_exception(*sys.exc_info(), limit, file)'."""
159
    print_exception(*sys.exc_info(), limit=limit, file=file, chain=chain)
160

161
def format_exc(limit=None, chain=True):
162
    """Like print_exc() but return a string."""
163
    return "".join(format_exception(*sys.exc_info(), limit=limit, chain=chain))
164

165
def print_last(limit=None, file=None, chain=True):
Tim Peters's avatar
Tim Peters committed
166 167
    """This is a shorthand for 'print_exception(sys.last_type,
    sys.last_value, sys.last_traceback, limit, file)'."""
Benjamin Peterson's avatar
Benjamin Peterson committed
168 169
    if not hasattr(sys, "last_type"):
        raise ValueError("no last exception")
Tim Peters's avatar
Tim Peters committed
170
    print_exception(sys.last_type, sys.last_value, sys.last_traceback,
171
                    limit, file, chain)
172

173 174 175 176
#
# Printing and Extracting Stacks.
#

177
def print_stack(f=None, limit=None, file=None):
178
    """Print a stack trace from its invocation point.
Tim Peters's avatar
Tim Peters committed
179

180 181 182 183
    The optional 'f' argument can be used to specify an alternate
    stack frame at which to start. The optional 'limit' and 'file'
    arguments have the same meaning as for print_exception().
    """
184 185
    if f is None:
        f = sys._getframe().f_back
186 187
    print_list(extract_stack(f, limit=limit), file=file)

188 189

def format_stack(f=None, limit=None):
190
    """Shorthand for 'format_list(extract_stack(f, limit))'."""
191 192
    if f is None:
        f = sys._getframe().f_back
193 194
    return format_list(extract_stack(f, limit=limit))

195

Georg Brandl's avatar
Georg Brandl committed
196
def extract_stack(f=None, limit=None):
197 198 199 200 201 202 203 204
    """Extract the raw traceback from the current stack frame.

    The return value has the same format as for extract_tb().  The
    optional 'f' and 'limit' arguments have the same meaning as for
    print_stack().  Each item in the list is a quadruple (filename,
    line number, function name, text), and the entries are in order
    from oldest to newest stack frame.
    """
205 206
    if f is None:
        f = sys._getframe().f_back
207
    stack = StackSummary.extract(walk_stack(f), limit=limit)
208 209
    stack.reverse()
    return stack
210

211

212 213 214 215 216 217 218 219 220
def clear_frames(tb):
    "Clear all references to local variables in the frames of a traceback."
    while tb is not None:
        try:
            tb.tb_frame.clear()
        except RuntimeError:
            # Ignore the exception raised if the frame is still executing.
            pass
        tb = tb.tb_next
221 222 223 224 225 226 227 228 229 230 231 232 233


class FrameSummary:
    """A single frame from a traceback.

    - :attr:`filename` The filename for the frame.
    - :attr:`lineno` The line within filename for the frame that was
      active when the frame was captured.
    - :attr:`name` The name of the function or method that was executing
      when the frame was captured.
    - :attr:`line` The text from the linecache module for the
      of code that was running when the frame was captured.
    - :attr:`locals` Either None if locals were not supplied, or a dict
234
      mapping the name to the repr() of the variable.
235 236 237 238
    """

    __slots__ = ('filename', 'lineno', 'name', '_line', 'locals')

239 240
    def __init__(self, filename, lineno, name, *, lookup_line=True,
            locals=None, line=None):
241 242 243 244 245
        """Construct a FrameSummary.

        :param lookup_line: If True, `linecache` is consulted for the source
            code line. Otherwise, the line will be looked up when first needed.
        :param locals: If supplied the frame locals, which will be captured as
246
            object representations.
247 248 249 250 251 252 253 254 255 256
        :param line: If provided, use this instead of looking up the line in
            the linecache.
        """
        self.filename = filename
        self.lineno = lineno
        self.name = name
        self._line = line
        if lookup_line:
            self.line
        self.locals = \
257
            dict((k, repr(v)) for k, v in locals.items()) if locals else None
258 259

    def __eq__(self, other):
260 261 262 263 264 265 266 267
        if isinstance(other, FrameSummary):
            return (self.filename == other.filename and
                    self.lineno == other.lineno and
                    self.name == other.name and
                    self.locals == other.locals)
        if isinstance(other, tuple):
            return (self.filename, self.lineno, self.name, self.line) == other
        return NotImplemented
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313

    def __getitem__(self, pos):
        return (self.filename, self.lineno, self.name, self.line)[pos]

    def __iter__(self):
        return iter([self.filename, self.lineno, self.name, self.line])

    def __repr__(self):
        return "<FrameSummary file {filename}, line {lineno} in {name}>".format(
            filename=self.filename, lineno=self.lineno, name=self.name)

    @property
    def line(self):
        if self._line is None:
            self._line = linecache.getline(self.filename, self.lineno).strip()
        return self._line


def walk_stack(f):
    """Walk a stack yielding the frame and line number for each frame.

    This will follow f.f_back from the given frame. If no frame is given, the
    current stack is used. Usually used with StackSummary.extract.
    """
    if f is None:
        f = sys._getframe().f_back.f_back
    while f is not None:
        yield f, f.f_lineno
        f = f.f_back


def walk_tb(tb):
    """Walk a traceback yielding the frame and line number for each frame.

    This will follow tb.tb_next (and thus is in the opposite order to
    walk_stack). Usually used with StackSummary.extract.
    """
    while tb is not None:
        yield tb.tb_frame, tb.tb_lineno
        tb = tb.tb_next


class StackSummary(list):
    """A stack of frames."""

    @classmethod
314 315
    def extract(klass, frame_gen, *, limit=None, lookup_lines=True,
            capture_locals=False):
316 317 318 319 320 321 322 323
        """Create a StackSummary from a traceback or stack object.

        :param frame_gen: A generator that yields (frame, lineno) tuples to
            include in the stack.
        :param limit: None to include all frames or the number of frames to
            include.
        :param lookup_lines: If True, lookup lines for each frame immediately,
            otherwise lookup is deferred until the frame is rendered.
324 325
        :param capture_locals: If True, the local variables from each frame will
            be captured as object representations into the FrameSummary.
326 327 328
        """
        if limit is None:
            limit = getattr(sys, 'tracebacklimit', None)
329 330 331 332 333 334 335
            if limit is not None and limit < 0:
                limit = 0
        if limit is not None:
            if limit >= 0:
                frame_gen = itertools.islice(frame_gen, limit)
            else:
                frame_gen = collections.deque(frame_gen, maxlen=-limit)
336 337 338

        result = klass()
        fnames = set()
339
        for f, lineno in frame_gen:
340 341 342 343 344 345 346
            co = f.f_code
            filename = co.co_filename
            name = co.co_name

            fnames.add(filename)
            linecache.lazycache(filename, f.f_globals)
            # Must defer line lookups until we have called checkcache.
347 348 349 350 351 352
            if capture_locals:
                f_locals = f.f_locals
            else:
                f_locals = None
            result.append(FrameSummary(
                filename, lineno, name, lookup_line=False, locals=f_locals))
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
        for filename in fnames:
            linecache.checkcache(filename)
        # If immediate lookup was desired, trigger lookups now.
        if lookup_lines:
            for f in result:
                f.line
        return result

    @classmethod
    def from_list(klass, a_list):
        """Create a StackSummary from a simple list of tuples.

        This method supports the older Python API. Each tuple should be a
        4-tuple with (filename, lineno, name, line) elements.
        """
368 369 370 371
        # While doing a fast-path check for isinstance(a_list, StackSummary) is
        # appealing, idlelib.run.cleanup_traceback and other similar code may
        # break this by making arbitrary frames plain tuples, so we need to
        # check on a frame by frame basis.
372
        result = StackSummary()
373 374 375 376 377 378
        for frame in a_list:
            if isinstance(frame, FrameSummary):
                result.append(frame)
            else:
                filename, lineno, name, line = frame
                result.append(FrameSummary(filename, lineno, name, line=line))
379 380 381 382 383 384 385 386 387
        return result

    def format(self):
        """Format the stack ready for printing.

        Returns a list of strings ready for printing.  Each string in the
        resulting list corresponds to a single frame from the stack.
        Each string ends in a newline; the strings may contain internal
        newlines as well, for those items with source text lines.
388 389 390 391

        For long sequences of the same frame and line, the first few
        repetitions are shown, followed by a summary line stating the exact
        number of further repetitions.
392 393
        """
        result = []
394 395 396 397
        last_file = None
        last_line = None
        last_name = None
        count = 0
398
        for frame in self:
399 400 401 402 403 404
            if (last_file is not None and last_file == frame.filename and
                last_line is not None and last_line == frame.lineno and
                last_name is not None and last_name == frame.name):
                count += 1
            else:
                if count > 3:
405
                    result.append(f'  [Previous line repeated {count-3} more times]'+'\n')
406 407 408 409 410 411
                last_file = frame.filename
                last_line = frame.lineno
                last_name = frame.name
                count = 0
            if count >= 3:
                continue
412 413 414 415 416 417 418 419 420
            row = []
            row.append('  File "{}", line {}, in {}\n'.format(
                frame.filename, frame.lineno, frame.name))
            if frame.line:
                row.append('    {}\n'.format(frame.line.strip()))
            if frame.locals:
                for name, value in sorted(frame.locals.items()):
                    row.append('    {name} = {value}\n'.format(name=name, value=value))
            result.append(''.join(row))
421
        if count > 3:
422
            result.append(f'  [Previous line repeated {count-3} more times]'+'\n')
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
        return result


class TracebackException:
    """An exception ready for rendering.

    The traceback module captures enough attributes from the original exception
    to this intermediary form to ensure that no references are held, while
    still being able to fully print or format it.

    Use `from_exception` to create TracebackException instances from exception
    objects, or the constructor to create TracebackException instances from
    individual components.

    - :attr:`__cause__` A TracebackException of the original *__cause__*.
    - :attr:`__context__` A TracebackException of the original *__context__*.
    - :attr:`__suppress_context__` The *__suppress_context__* value from the
      original exception.
    - :attr:`stack` A `StackSummary` representing the traceback.
    - :attr:`exc_type` The class of the original traceback.
    - :attr:`filename` For syntax errors - the filename where the error
444
      occurred.
445
    - :attr:`lineno` For syntax errors - the linenumber where the error
446
      occurred.
447
    - :attr:`text` For syntax errors - the text where the error
448
      occurred.
449
    - :attr:`offset` For syntax errors - the offset into the text where the
450
      error occurred.
451 452 453
    - :attr:`msg` For syntax errors - the compiler error message.
    """

454 455
    def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
            lookup_lines=True, capture_locals=False, _seen=None):
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
        # NB: we need to accept exc_traceback, exc_value, exc_traceback to
        # permit backwards compat with the existing API, otherwise we
        # need stub thunk objects just to glue it together.
        # Handle loops in __cause__ or __context__.
        if _seen is None:
            _seen = set()
        _seen.add(exc_value)
        # Gracefully handle (the way Python 2.4 and earlier did) the case of
        # being called with no type or value (None, None, None).
        if (exc_value and exc_value.__cause__ is not None
            and exc_value.__cause__ not in _seen):
            cause = TracebackException(
                type(exc_value.__cause__),
                exc_value.__cause__,
                exc_value.__cause__.__traceback__,
                limit=limit,
                lookup_lines=False,
473
                capture_locals=capture_locals,
474 475 476 477 478 479 480 481 482 483 484
                _seen=_seen)
        else:
            cause = None
        if (exc_value and exc_value.__context__ is not None
            and exc_value.__context__ not in _seen):
            context = TracebackException(
                type(exc_value.__context__),
                exc_value.__context__,
                exc_value.__context__.__traceback__,
                limit=limit,
                lookup_lines=False,
485
                capture_locals=capture_locals,
486 487 488
                _seen=_seen)
        else:
            context = None
489
        self.exc_traceback = exc_traceback
490 491 492 493 494 495
        self.__cause__ = cause
        self.__context__ = context
        self.__suppress_context__ = \
            exc_value.__suppress_context__ if exc_value else False
        # TODO: locals.
        self.stack = StackSummary.extract(
496 497
            walk_tb(exc_traceback), limit=limit, lookup_lines=lookup_lines,
            capture_locals=capture_locals)
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
        self.exc_type = exc_type
        # Capture now to permit freeing resources: only complication is in the
        # unofficial API _format_final_exc_line
        self._str = _some_str(exc_value)
        if exc_type and issubclass(exc_type, SyntaxError):
            # Handle SyntaxError's specially
            self.filename = exc_value.filename
            self.lineno = str(exc_value.lineno)
            self.text = exc_value.text
            self.offset = exc_value.offset
            self.msg = exc_value.msg
        if lookup_lines:
            self._load_lines()

    @classmethod
513
    def from_exception(cls, exc, *args, **kwargs):
514
        """Create a TracebackException from an exception."""
515
        return cls(type(exc), exc, exc.__traceback__, *args, **kwargs)
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576

    def _load_lines(self):
        """Private API. force all lines in the stack to be loaded."""
        for frame in self.stack:
            frame.line
        if self.__context__:
            self.__context__._load_lines()
        if self.__cause__:
            self.__cause__._load_lines()

    def __eq__(self, other):
        return self.__dict__ == other.__dict__

    def __str__(self):
        return self._str

    def format_exception_only(self):
        """Format the exception part of the traceback.

        The return value is a generator of strings, each ending in a newline.

        Normally, the generator emits a single string; however, for
        SyntaxError exceptions, it emites several lines that (when
        printed) display detailed information about where the syntax
        error occurred.

        The message indicating which exception occurred is always the last
        string in the output.
        """
        if self.exc_type is None:
            yield _format_final_exc_line(None, self._str)
            return

        stype = self.exc_type.__qualname__
        smod = self.exc_type.__module__
        if smod not in ("__main__", "builtins"):
            stype = smod + '.' + stype

        if not issubclass(self.exc_type, SyntaxError):
            yield _format_final_exc_line(stype, self._str)
            return

        # It was a syntax error; show exactly where the problem was found.
        filename = self.filename or "<string>"
        lineno = str(self.lineno) or '?'
        yield '  File "{}", line {}\n'.format(filename, lineno)

        badline = self.text
        offset = self.offset
        if badline is not None:
            yield '    {}\n'.format(badline.strip())
            if offset is not None:
                caretspace = badline.rstrip('\n')
                offset = min(len(caretspace), offset) - 1
                caretspace = caretspace[:offset].lstrip()
                # non-space whitespace (likes tabs) must be kept for alignment
                caretspace = ((c.isspace() and c or ' ') for c in caretspace)
                yield '    {}^\n'.format(''.join(caretspace))
        msg = self.msg or "<no detail available>"
        yield "{}: {}\n".format(stype, msg)

577
    def format(self, *, chain=True):
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
        """Format the exception.

        If chain is not *True*, *__cause__* and *__context__* will not be formatted.

        The return value is a generator of strings, each ending in a newline and
        some containing internal newlines. `print_exception` is a wrapper around
        this method which just prints the lines to a file.

        The message indicating which exception occurred is always the last
        string in the output.
        """
        if chain:
            if self.__cause__ is not None:
                yield from self.__cause__.format(chain=chain)
                yield _cause_message
            elif (self.__context__ is not None and
                not self.__suppress_context__):
                yield from self.__context__.format(chain=chain)
                yield _context_message
597 598
        if self.exc_traceback is not None:
            yield 'Traceback (most recent call last):\n'
599 600
        yield from self.stack.format()
        yield from self.format_exception_only()