print_exc_plus : 8.6. Getting More Information from Tracebacks


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. import sys, traceback
  2. def print_exc_plus( ):
  3. """ Print the usual traceback information, followed by a listing of
  4. all the local variables in each frame.
  5. """
  6. tb = sys.exc_info( )[2]
  7. while tb.tb_next:
  8. tb = tb.tb_next
  9. stack = [ ]
  10. f = tb.tb_frame
  11. while f:
  12. stack.append(f)
  13. f = f.f_back
  14. stack.reverse( )
  15. traceback.print_exc( )
  16. print "Locals by frame, innermost last"
  17. for frame in stack:
  18. print
  19. print "Frame %s in %s at line %s" % (frame.f_code.co_name,
  20. frame.f_code.co_filename,
  21. frame.f_lineno)
  22. for key, value in frame.f_locals.items( ):
  23. print "\t%20s = " % key,
  24. # we must _absolutely_ avoid propagating exceptions, and str(value)
  25. # COULD cause any exception, so we MUST catch any...:
  26. try:
  27. print value
  28. except:
  29. print "<ERROR WHILE PRINTING VALUE>"
  30.  
  31. data = ["1", "2", 3, "4"] # Typo: we 'forget' the quotes on data[2]
  32. def pad4(seq):
  33. """
  34. Pad each string in seq with zeros up to four places. Note that there
  35. is no reason to actually write this function; Python already
  36. does this sort of thing much better. It's just an example!
  37. """
  38. return_value = [ ]
  39. for thing in seq:
  40. return_value.append("0" * (4 - len(thing)) + thing)
  41. return return_value
  42.  
  43.  
  44. Here's the (limited) information we get from a normal traceback.print_exc:
  45.  
  46. >>> try:
  47. ... pad4(data)
  48. ... except:
  49. ... traceback.print_exc( )
  50. ...
  51. Traceback (most recent call last):
  52. File "<stdin>", line 2, in ?
  53. File "<stdin>", line 9, in pad4
  54. TypeError: len( ) of unsized object
  55.  
  56. >>> try:
  57. ... pad4(data)
  58. ... except:
  59. ... print_exc_plus( )
  60. ...
  61. Traceback (most recent call last):
  62. File "<stdin>", line 2, in ?
  63. File "<stdin>", line 9, in pad4
  64. TypeError: len( ) of unsized object
  65. Locals by frame, innermost last
  66. Frame ? in <stdin> at line 4
  67. sys = <module>
  68. pad4 = <function>
  69. _ _builtins_ _ = <module>
  70. _ _name_ _ = _ _main_ _
  71. data = ['1', '2', 3, '4']
  72. _ _doc_ _ = None
  73. print_exc_plus = <function>
  74. Frame pad4 in <stdin> at line 9
  75. thing = 3
  76. return_value = ['0001', '0002']
  77. seq = ['1', '2', 3, '4']

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.