You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.7KB

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