lineno and filename in exceptions

Michael P. Reilly arcege at shore.net
Tue Oct 5 10:49:45 EDT 1999


Udo Gleich <Udo.Gleich at gmx.de> wrote:
: Hi,

: I would like to catch syntax errors and other errors in script
: files and open an editor at the right line number.

: If I catch a syntax error the exeption has the attributes lineno and
: filename. This information is not included e.g. in attribute errors
: name errors.

The exception traceback object contains this information (indirectly).
The traceback module has an "extract_tb" function which returns a list
of tuples containing the information you want (filename, lineno,
functname, line_contents).  You need to import sys and traceback before
the exception is raised.

  import sys, traceback
  def return_exception_file_info():
    tb = sys.exc_info()[2]
    last_frame = traceback.extract_tb(tb)[-1]
    filename, lineno, funct, contents = last_frame
    return (filename, lineno)

The list contains the location inside each frame where the exception
was raised (which came be more useful than just the filename and lineno
of the originating code).

For example:
  ...
  def f():
    g
  def e():
    f()

  try:
    e()
  except:
    print traceback.extract_tb(sys.exc_info()[2])
[('trace.py', 11, '?', 'e()'), ('trace.py', 8, 'e', 'f()'), ('trace.py',
6, 'f', 'g')]

It would be good to read up on the "traceback" module:
<URL: http://www.python.org/doc/current/lib/module-traceback.html>

  -Arcege





More information about the Python-list mailing list