Get Stack Trace in “except” Block

6 thoughts on “Get Stack Trace in “except” Block

  1. I am trying to log execeptions using a try/except block and I was wondering if anyone has any sample code for extracting a stack trace from the exc_info()  call.  

     

    Most examples on the web make use of the “traceback” module for getting stack traces. This module is not included with the embedded 1.5.2. Telit python.  At the very least, it would be nice to extract the module name and line number of where the execption occurred.

     

    Can anyone provide a sample? 

     

     

     

     

    1. There is an example in Telit Python Examples r3 in Download Zone, traceback_1.py file:

       

      def tb_lineno(tb):
        # Coded by xxxxxxx from the example of PyCode_Addr2Line()
        # in compile.c.
        # Revised version by yyyyyyy to work with JPython too.
        c = tb.tb_frame.f_code
        if not hasattr(tb.tb_frame.f_code, ‘co_lnotab’):
          return tb.tb_lineno

        line = tb.tb_frame.f_code.co_firstlineno
        addr = 0
        for i in range(0, len(tb.tb_frame.f_code.co_lnotab), 2):
          addr = addr + ord(tb.tb_frame.f_code.co_lnotab[i])
          if addr > tb.tb_lasti:
            break
          line = line + ord(tb.tb_frame.f_code.co_lnotab[i+1])
        return line

      def main():
          print ‘traceback_1.pyrn© 2009 Telit Communicationsr’
          r = 1 + ‘ ‘ # we generate an exception here

      try:
        main()
      except:
        # we catch it
        import sys
        type, value, tb = sys.exc_info()
        # we get the exception caracteristics
        print’============= An Exception occurs ============’
        print ‘Exception :’, type, ‘=’, value
        while tb is not None :
          print ‘  File "%s", line %d, in %s’ %
            (tb.tb_frame.f_code.co_filename,
             tb_lineno(tb),tb.tb_frame.f_code.co_name)
          tb = tb.tb_next
        # we transform the traceback exception in a string format.

        1. Hi Cosmin

           

          Thanks for posting the example. Seems working, just tried it. But can you explain the meaning of the three first lines:

           

          c = tb.tb_frame.f_code
          if not hasattr(tb.tb_frame.f_code, ‘co_lnotab’):
              return tb.tb_lineno

          Anyway, I think I will use this somehow in my future scripts.

           

          BR, Tom