| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
import types |
| 6 |
|
| 7 |
def format_exception_only(etype, value): |
| 8 |
"""Format the exception part of a traceback. |
| 9 |
|
| 10 |
The arguments are the exception type and value such as given by |
| 11 |
sys.last_type and sys.last_value. The return value is a list of |
| 12 |
strings, each ending in a newline. |
| 13 |
|
| 14 |
Normally, the list contains a single string; however, for |
| 15 |
SyntaxError exceptions, it contains several lines that (when |
| 16 |
printed) display detailed information about where the syntax |
| 17 |
error occurred. |
| 18 |
|
| 19 |
The message indicating which exception occurred is always the last |
| 20 |
string in the list. |
| 21 |
|
| 22 |
""" |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
if (isinstance(etype, BaseException) or |
| 31 |
isinstance(etype, types.InstanceType) or |
| 32 |
etype is None or type(etype) is str): |
| 33 |
return [_format_final_exc_line(etype, value)] |
| 34 |
|
| 35 |
stype = etype.__name__ |
| 36 |
|
| 37 |
if not issubclass(etype, SyntaxError): |
| 38 |
return [_format_final_exc_line(stype, value)] |
| 39 |
|
| 40 |
|
| 41 |
lines = [] |
| 42 |
try: |
| 43 |
msg, (filename, lineno, offset, badline) = value.args |
| 44 |
except Exception: |
| 45 |
pass |
| 46 |
else: |
| 47 |
filename = filename or "<string>" |
| 48 |
lines.append(' File "%s", line %d\n' % (filename, lineno)) |
| 49 |
if badline is not None: |
| 50 |
lines.append(' %s\n' % badline.strip()) |
| 51 |
if offset is not None: |
| 52 |
caretspace = badline.rstrip('\n')[:offset].lstrip() |
| 53 |
|
| 54 |
caretspace = ((c.isspace() and c or ' ') for c in caretspace) |
| 55 |
|
| 56 |
lines.append(' %s^\n' % ''.join(caretspace)) |
| 57 |
value = msg |
| 58 |
|
| 59 |
lines.append(_format_final_exc_line(stype, value)) |
| 60 |
return lines |
| 61 |
|
| 62 |
def _format_final_exc_line(etype, value): |
| 63 |
"""Return a list of a single line -- normal case for format_exception_only""" |
| 64 |
valuestr = _some_str(value) |
| 65 |
if value is None or not valuestr: |
| 66 |
line = "%s\n" % etype |
| 67 |
else: |
| 68 |
line = "%s: %s\n" % (etype, valuestr) |
| 69 |
return line |
| 70 |
|
| 71 |
def _some_str(value): |
| 72 |
try: |
| 73 |
return unicode(value) |
| 74 |
except Exception: |
| 75 |
try: |
| 76 |
return str(value) |
| 77 |
except Exception: |
| 78 |
pass |
| 79 |
return '<unprintable %s object>' % type(value).__name__ |