_py2traceback.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # copied from python-2.7.3's traceback.py
  2. # CHANGES:
  3. # - some_str is replaced, trying to create unicode strings
  4. #
  5. from __future__ import absolute_import, division, print_function, unicode_literals
  6. import types
  7. from six import text_type
  8. def format_exception_only(etype, value):
  9. """Format the exception part of a traceback.
  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. Normally, the list contains a single string; however, for
  14. SyntaxError exceptions, it contains several lines that (when
  15. printed) display detailed information about where the syntax
  16. error occurred.
  17. The message indicating which exception occurred is always the last
  18. string in the list.
  19. """
  20. # An instance should not have a meaningful value parameter, but
  21. # sometimes does, particularly for string exceptions, such as
  22. # >>> raise string1, string2 # deprecated
  23. #
  24. # Clear these out first because issubtype(string1, SyntaxError)
  25. # would throw another exception and mask the original problem.
  26. if (
  27. isinstance(etype, BaseException)
  28. or isinstance(etype, types.InstanceType)
  29. or etype is None
  30. or type(etype) is str
  31. ):
  32. return [_format_final_exc_line(etype, value)]
  33. stype = etype.__name__
  34. if not issubclass(etype, SyntaxError):
  35. return [_format_final_exc_line(stype, value)]
  36. # It was a syntax error; show exactly where the problem was found.
  37. lines = []
  38. try:
  39. msg, (filename, lineno, offset, badline) = value.args
  40. except Exception:
  41. pass
  42. else:
  43. filename = filename or "<string>"
  44. lines.append(' File "{}", line {}\n'.format(filename, lineno))
  45. if badline is not None:
  46. if isinstance(badline, bytes): # python 2 only
  47. badline = badline.decode("utf-8", "replace")
  48. lines.append(" {}\n".format(badline.strip()))
  49. if offset is not None:
  50. caretspace = badline.rstrip("\n")[:offset].lstrip()
  51. # non-space whitespace (likes tabs) must be kept for alignment
  52. caretspace = ((c.isspace() and c or " ") for c in caretspace)
  53. # only three spaces to account for offset1 == pos 0
  54. lines.append(" {}^\n".format("".join(caretspace)))
  55. value = msg
  56. lines.append(_format_final_exc_line(stype, value))
  57. return lines
  58. def _format_final_exc_line(etype, value):
  59. """Return a list of a single line -- normal case for format_exception_only"""
  60. valuestr = _some_str(value)
  61. if value is None or not valuestr:
  62. line = "{}\n".format(etype)
  63. else:
  64. line = "{}: {}\n".format(etype, valuestr)
  65. return line
  66. def _some_str(value):
  67. try:
  68. return text_type(value)
  69. except Exception:
  70. try:
  71. return bytes(value).decode("UTF-8", "replace")
  72. except Exception:
  73. pass
  74. return "<unprintable {} object>".format(type(value).__name__)