Path: blob/main/python/pylang/src/lib/traceback.py
1398 views
# vim:fileencoding=utf-81# License: BSD Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>2# globals: ρσ_str, ρσ_last_exception345def _get_internal_traceback(err):6if isinstance(err, Exception) and err.stack:7lines = ρσ_str.splitlines(err.stack)8final_lines = v'[]'9found_sentinel = False10for i, line in enumerate(lines):11sline = ρσ_str.strip(line)12if i is 0:13final_lines.push(line)14continue15if found_sentinel:16final_lines.push(line)17continue18# These two conditions work on desktop Chrome and Firefox to identify the correct19# line in the traceback.20if sline.startsWith('at new ' + err.name) or sline.startsWith(err.name + '@'):21found_sentinel = True22return final_lines.join('\n')23return err and err.stack2425def format_exception(exc, limit):26if jstype(exc) is 'undefined':27exc = ρσ_last_exception28if not isinstance(exc, Error):29if exc and exc.toString:30return [exc.toString()]31return []32tb = _get_internal_traceback(exc)33if tb:34lines = ρσ_str.splitlines(tb)35e = lines[0]36lines = lines[1:]37if limit:38lines = lines[:limit+1] if limit > 0 else lines[limit:]39lines.reverse()40lines.push(e)41lines.insert(0, 'Traceback (most recent call last):')42return [l+'\n' for l in lines]43return [exc.toString()]4445def format_exc(limit):46return format_exception(ρσ_last_exception, limit).join('')4748def print_exc(limit):49print(format_exc(limit))5051def format_stack(limit):52stack = Error().stack53if not stack:54return []55lines = str.splitlines(stack)[2:]56lines.reverse()57if limit:58lines = lines[:limit+1] if limit > 0 else lines[limit:]59return [l + '\n' for l in lines]6061def print_stack(limit):62print(format_stack(limit).join(''))636465