Manually printing traceback?

Graham Dumpleton grahamd at dscpl.com.au
Wed Aug 8 07:24:42 CEST 2001


sill at optonline.net (Andrei Kulakov) wrote in message news:<slrn9n18po.19r.sill at sill.silmarill.org>...
> Hello,
> 
> If I run this code: l = []; print l[1], I get a traceback.
> If I change it to:
> 
> import sys
> l = []
> try: print l[1]
> except:
>     print sys.exc_info()
> 
> I get a tuple, 3rd element of which is the traceback object. How do i print
> it? I tried doing print sys.exc_info()[2]() but that doesn't work. I also
> read libref and langref and i couldn't find anything enlightening on this.
> I found a post where paul prescott asks a similar question and gvr tells him
> that you basically have to read code for some debugger, or something of this
> sort.. that's over my head, i'm afraid.
> 
> The reason i ask is that my program (cymbaline) doesn't print out exceptions
> that it raises. I have no idea why.. I don't have any big chunks in try:
> except: catch-all blocks.. So, alternatively, if i knew what else could be
> causing this, i wouldn't need the answer the my first question. I just need
> the answer to either one :P

There is the traceback module.

  try:
    ...
  except:
    traceback.print_exc()

If you want a function to deal with the traceback object directly so as to
format the traceback in a string and use it in some other way, ie., log it,
you can use:

def exceptionDetails(skip=0):
  info = sys.exc_info()
  exc_type = info[0]
  exc_value = info[1]
  exc_traceback = info[2]
  trace = traceback.extract_tb(exc_traceback)
  trace = trace[skip:]
  error = "Python Exception\n"
  try:
    where = "Module: " + str(callback.im_class.__module__) + "\n"
    where = where + "Method: " + str(callback.im_class.__name__)
    where = where + "." + str(callback.__name__) + "\n"
  except:
    try:
      where = "Function: " + str(callback.__name__) + "\n"
    except:
      where = ""
  error = error + where
  error = error + "Traceback (innermost last):\n"
  for filename,lineno,function,message in trace:
    error = error + "  File \"" + filename +  "\""
    error = error + ", line " + str(lineno)
    error = error + ", in " + function + "\n"
    if message:
      error = error + "    " + message + "\n"
  error = error + str(exc_type) + ": " + str(exc_value)
  return error

BTW, be careful about accessing traceback objects directly in except clause
of member function of object as you can end up with circular references
meaning that object instance will not be destroyed. Some note in tex files
of Python distribution about this, but haven't seen it documented in any
printed books. Easiest thing to do is to access it from a separate global
scope function as above.



More information about the Python-list mailing list