Guido van Rossum | 526beed | 1994-07-01 15:36:46 +0000 | [diff] [blame] | 1 | # Format and print Python stack traces |
| 2 | |
| 3 | import linecache |
| 4 | import string |
| 5 | import sys |
| 6 | |
| 7 | def print_tb(tb, limit = None): |
| 8 | if limit is None: |
| 9 | if hasattr(sys, 'tracebacklimit'): |
| 10 | limit = sys.tracebacklimit |
| 11 | n = 0 |
| 12 | while tb is not None and (limit is None or n < limit): |
| 13 | f = tb.tb_frame |
| 14 | lineno = tb.tb_lineno |
| 15 | co = f.f_code |
| 16 | filename = co.co_filename |
| 17 | name = co.co_name |
| 18 | print ' File "%s", line %d, in %s' % (filename, lineno, name) |
| 19 | line = linecache.getline(filename, lineno) |
| 20 | if line: print ' ' + string.strip(line) |
| 21 | tb = tb.tb_next |
| 22 | n = n+1 |
| 23 | |
| 24 | def extract_tb(tb, limit = None): |
| 25 | if limit is None: |
| 26 | if hasattr(sys, 'tracebacklimit'): |
| 27 | limit = sys.tracebacklimit |
| 28 | list = [] |
| 29 | n = 0 |
| 30 | while tb is not None and (limit is None or n < limit): |
| 31 | f = tb.tb_frame |
| 32 | lineno = tb.tb_lineno |
| 33 | co = f.f_code |
| 34 | filename = co.co_filename |
| 35 | name = co.co_name |
| 36 | line = linecache.getline(filename, lineno) |
| 37 | if line: line = string.strip(line) |
| 38 | else: line = None |
| 39 | list.append(filename, lineno, name, line) |
| 40 | tb = tb.tb_next |
| 41 | n = n+1 |
| 42 | return list |
| 43 | |
| 44 | def print_exception(type, value, tb, limit = None): |
| 45 | print 'Traceback (innermost last):' |
| 46 | print_tb(tb, limit) |
| 47 | print type, |
| 48 | if value is not None: print ':', value, |
| 49 | print |
| 50 | |
| 51 | def print_exc(limit = None): |
| 52 | print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, |
| 53 | limit) |
| 54 | |
| 55 | def print_last(limit = None): |
| 56 | print_exception(sys.last_type, sys.last_value, sys.last_traceback, |
| 57 | limit) |