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): |
Guido van Rossum | 7aeb4b9 | 1994-08-23 13:32:20 +0000 | [diff] [blame] | 45 | if tb: |
| 46 | print 'Traceback (innermost last):' |
| 47 | print_tb(tb, limit) |
| 48 | if value is None: |
| 49 | print type |
| 50 | else: |
| 51 | if type is SyntaxError: |
| 52 | try: |
| 53 | msg, (filename, lineno, offset, line) = value |
| 54 | except: |
| 55 | pass |
| 56 | else: |
| 57 | if not filename: filename = "<string>" |
| 58 | print ' File "%s", line %d' % (filename, lineno) |
| 59 | i = 0 |
| 60 | while i < len(line) and line[i] in string.whitespace: |
| 61 | i = i+1 |
| 62 | s = ' ' |
| 63 | print s + string.strip(line) |
| 64 | for c in line[i:offset-1]: |
| 65 | if c in string.whitespace: |
| 66 | s = s + c |
| 67 | else: |
| 68 | s = s + ' ' |
| 69 | print s + '^' |
| 70 | value = msg |
| 71 | print '%s: %s' % (type, value) |
Guido van Rossum | 526beed | 1994-07-01 15:36:46 +0000 | [diff] [blame] | 72 | |
| 73 | def print_exc(limit = None): |
| 74 | print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, |
| 75 | limit) |
| 76 | |
| 77 | def print_last(limit = None): |
| 78 | print_exception(sys.last_type, sys.last_value, sys.last_traceback, |
| 79 | limit) |