Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/python-wasm
Path: blob/main/python/pylang/src/lib/traceback.py
1398 views
1
# vim:fileencoding=utf-8
2
# License: BSD Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
3
# globals: ρσ_str, ρσ_last_exception
4
5
6
def _get_internal_traceback(err):
7
if isinstance(err, Exception) and err.stack:
8
lines = ρσ_str.splitlines(err.stack)
9
final_lines = v'[]'
10
found_sentinel = False
11
for i, line in enumerate(lines):
12
sline = ρσ_str.strip(line)
13
if i is 0:
14
final_lines.push(line)
15
continue
16
if found_sentinel:
17
final_lines.push(line)
18
continue
19
# These two conditions work on desktop Chrome and Firefox to identify the correct
20
# line in the traceback.
21
if sline.startsWith('at new ' + err.name) or sline.startsWith(err.name + '@'):
22
found_sentinel = True
23
return final_lines.join('\n')
24
return err and err.stack
25
26
def format_exception(exc, limit):
27
if jstype(exc) is 'undefined':
28
exc = ρσ_last_exception
29
if not isinstance(exc, Error):
30
if exc and exc.toString:
31
return [exc.toString()]
32
return []
33
tb = _get_internal_traceback(exc)
34
if tb:
35
lines = ρσ_str.splitlines(tb)
36
e = lines[0]
37
lines = lines[1:]
38
if limit:
39
lines = lines[:limit+1] if limit > 0 else lines[limit:]
40
lines.reverse()
41
lines.push(e)
42
lines.insert(0, 'Traceback (most recent call last):')
43
return [l+'\n' for l in lines]
44
return [exc.toString()]
45
46
def format_exc(limit):
47
return format_exception(ρσ_last_exception, limit).join('')
48
49
def print_exc(limit):
50
print(format_exc(limit))
51
52
def format_stack(limit):
53
stack = Error().stack
54
if not stack:
55
return []
56
lines = str.splitlines(stack)[2:]
57
lines.reverse()
58
if limit:
59
lines = lines[:limit+1] if limit > 0 else lines[limit:]
60
return [l + '\n' for l in lines]
61
62
def print_stack(limit):
63
print(format_stack(limit).join(''))
64
65