Python equivalent of __LINE__ macro?

Hans Nowak wurmy at earthlink.net
Mon Jan 7 12:41:33 EST 2002


David Brady wrote:
> 
> Hello,
> 
> I'm writing a set of Python scripts to be integrated
> with Developer Studio as part of a custom build.  If
> the script encounters an error, I'd like to be able to
> print the line number the error happened, so that
> DevStoo users can hit F4 and be taken to the offending
> script line.
> 
> Is there an easy way to do this?  The handiest thing
> would be to have a variable like __LINE__ hanging
> around, but in a pinch I suppose we could just use the
> traceback and trap all exceptions....  Though I wonder
> if there isn't an easier way.

This one is from the snippets repository I once had.

#---begin---

# 176.py
# Author: Fredrik Lundh
# Subject: Lineno and filename in exceptions
# 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

#---end---

--Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==') 
       # decode for email address ;-)
Site:: http://www.awaretek.com/nowak/



More information about the Python-list mailing list