faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 2 people (100%) answered Yes
Recently 1 of 1 people (100%) answered Yes

Entry

Lineno and filename in exceptions

Jul 5th, 2000 10:00
Nathan Wallace, Hans Nowak, Snippet 176, Fredrik Lundh


"""
Packages: miscellaneous.introspection
"""
"""
> 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.
> Question: Is there a way to get line number and file name in errors
> other than SyntaxError?
you can dissect traceback, frame, and
code objects to get the required info.
here's an example:
"""
import sys, traceback
try:
    execfile("script.py")
except Exception, argument:
    et, ev, tb = sys.exc_info()
    while tb:
        co = tb.tb_frame.f_code
        print co.co_filename,
        print traceback.tb_lineno(tb)
        tb = tb.tb_next
    print et, ev