| 1 | import traceback |
| 2 | |
| 3 | |
| 4 | def format_exception(exception): |
| 5 | """Format an exception as diagnostics output. |
| 6 | |
| 7 | exception is the tuple as expected from sys.exc_info. |
| 8 | """ |
| 9 | exception_lines = traceback.format_exception(*exception) |
| 10 | # The lines returned from format_exception do not strictly contain |
| 11 | # one line per element in the list (i.e. some elements have new |
| 12 | # line characters in the middle). Normalize that oddity. |
| 13 | lines = ''.join(exception_lines).splitlines(True) |
| 14 | return format_as_diagnostics(lines) |
| 15 | |
| 16 | |
| 17 | def format_as_diagnostics(lines): |
| 18 | """Format the lines as diagnostics output by prepending the diagnostic #. |
| 19 | |
| 20 | This function makes no assumptions about the line endings. |
| 21 | """ |
| 22 | return ''.join(['# ' + line for line in lines]) |