1 # Format and print Python stack traces
8 def _print(file, str='', terminator
='\n'):
9 file.write(str+terminator
)
12 def print_tb(tb
, limit
=None, file=None):
16 if hasattr(sys
, 'tracebacklimit'):
17 limit
= sys
.tracebacklimit
19 while tb
is not None and (limit
is None or n
< limit
):
23 filename
= co
.co_filename
26 ' File "%s", line %d, in %s' % (filename
,lineno
,name
))
27 line
= linecache
.getline(filename
, lineno
)
28 if line
: _print(file, ' ' + string
.strip(line
))
32 def format_tb(tb
, limit
= None):
34 for filename
, lineno
, name
, line
in extract_tb(tb
, limit
):
35 item
= ' File "%s", line %d, in %s\n' % (filename
,lineno
,name
)
37 item
= item
+ ' %s\n' % string
.strip(line
)
41 def extract_tb(tb
, limit
= None):
43 if hasattr(sys
, 'tracebacklimit'):
44 limit
= sys
.tracebacklimit
47 while tb
is not None and (limit
is None or n
< limit
):
51 filename
= co
.co_filename
53 line
= linecache
.getline(filename
, lineno
)
54 if line
: line
= string
.strip(line
)
56 list.append(filename
, lineno
, name
, line
)
62 def print_exception(etype
, value
, tb
, limit
=None, file=None):
66 _print(file, 'Traceback (innermost last):')
67 print_tb(tb
, limit
, file)
68 lines
= format_exception_only(etype
, value
)
69 for line
in lines
[:-1]:
70 _print(file, line
, ' ')
71 _print(file, lines
[-1], '')
73 def format_exception(etype
, value
, tb
, limit
= None):
75 list = ['Traceback (innermost last):\n']
76 list = list + format_tb(tb
, limit
)
77 list = list + format_exception_only(etype
, value
)
80 def format_exception_only(etype
, value
):
82 if type(etype
) == types
.ClassType
:
83 stype
= etype
.__name
__
87 list.append(str(stype
) + '\n')
89 if etype
is SyntaxError:
91 msg
, (filename
, lineno
, offset
, line
) = value
95 if not filename
: filename
= "<string>"
96 list.append(' File "%s", line %d\n' %
99 while i
< len(line
) and \
100 line
[i
] in string
.whitespace
:
102 list.append(' %s\n' % string
.strip(line
))
104 for c
in line
[i
:offset
-1]:
105 if c
in string
.whitespace
:
109 list.append('%s^\n' % s
)
111 list.append('%s: %s\n' % (str(stype
), str(value
)))
115 def print_exc(limit
=None, file=None):
118 print_exception(sys
.exc_type
, sys
.exc_value
, sys
.exc_traceback
,
121 def print_last(limit
=None, file=None):
124 print_exception(sys
.last_type
, sys
.last_value
, sys
.last_traceback
,