1 # Format and print Python stack traces
3 # updated to take optional "file" named parameter
4 # by Tommy Burnette, 9/20/95
11 def _print(file, str='', terminator
='\n'):
12 file.write(str+terminator
)
15 def print_tb(tb
, limit
=None, file=None):
19 if hasattr(sys
, 'tracebacklimit'):
20 limit
= sys
.tracebacklimit
22 while tb
is not None and (limit
is None or n
< limit
):
26 filename
= co
.co_filename
29 ' File "%s", line %d, in %s' % (filename
,lineno
,name
))
30 line
= linecache
.getline(filename
, lineno
)
31 if line
: _print(file, ' ' + string
.strip(line
))
35 def format_tb(tb
, limit
= None):
37 for filename
, lineno
, name
, line
in extract_tb(tb
, limit
):
38 item
= ' File "%s", line %d, in %s\n' % (filename
,lineno
,name
)
40 item
= item
+ ' %s\n' % string
.strip(line
)
44 def extract_tb(tb
, limit
= None):
46 if hasattr(sys
, 'tracebacklimit'):
47 limit
= sys
.tracebacklimit
50 while tb
is not None and (limit
is None or n
< limit
):
54 filename
= co
.co_filename
56 line
= linecache
.getline(filename
, lineno
)
57 if line
: line
= string
.strip(line
)
59 list.append(filename
, lineno
, name
, line
)
65 def print_exception(etype
, value
, tb
, limit
=None, file=None):
69 _print(file, 'Traceback (innermost last):')
70 print_tb(tb
, limit
, file)
71 lines
= format_exception_only(etype
, value
)
72 for line
in lines
[:-1]:
73 _print(file, line
, ' ')
74 _print(file, lines
[-1], '')
76 def format_exception(etype
, value
, tb
, limit
= None):
78 list = ['Traceback (innermost last):\n']
79 list = list + format_tb(tb
, limit
)
80 list = list + format_exception_only(etype
, value
)
83 def format_exception_only(etype
, value
):
85 if type(etype
) == types
.ClassType
:
86 stype
= etype
.__name
__
90 list.append(str(stype
) + '\n')
92 if etype
is SyntaxError:
94 msg
, (filename
, lineno
, offset
, line
) = value
98 if not filename
: filename
= "<string>"
99 list.append(' File "%s", line %d\n' %
102 while i
< len(line
) and \
103 line
[i
] in string
.whitespace
:
105 list.append(' %s\n' % string
.strip(line
))
107 for c
in line
[i
:offset
-1]:
108 if c
in string
.whitespace
:
112 list.append('%s^\n' % s
)
114 list.append('%s: %s\n' % (str(stype
), str(value
)))
118 def print_exc(limit
=None, file=None):
121 print_exception(sys
.exc_type
, sys
.exc_value
, sys
.exc_traceback
,
124 def print_last(limit
=None, file=None):
127 print_exception(sys
.last_type
, sys
.last_value
, sys
.last_traceback
,