getting source code line of error?

Ulli Horlacher framstag at rus.uni-stuttgart.de
Fri Nov 19 07:09:26 EST 2021


I am trying to get the source code line of the last error.
I know traceback.format_exc() but this contains much more information, e.g.:

Traceback (most recent call last):
  File "./error.py", line 18, in main
    x=1/0
ZeroDivisionError: division by zero

I could extract the source code line with re.search(), but is there an
easier way?


I have:

      exc_type,exc_str,exc_tb = sys.exc_info()
      fname = exc_tb.tb_frame.f_code.co_filename
      line = exc_tb.tb_lineno
      print('%s in %s line %d' % (exc_str,fname,line))

But I also want to output the line itself, not only its number.

-- 
Ullrich Horlacher              Server und Virtualisierung
Rechenzentrum TIK         
Universitaet Stuttgart         E-Mail: horlacher at tik.uni-stuttgart.de
Allmandring 30a                Tel:    ++49-711-68565868
70569 Stuttgart (Germany)      WWW:    http://www.tik.uni-stuttgart.de/


More information about the Python-list mailing list