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?

1 of 1 people (100%) answered Yes

Entry

Syntax checking & catching exceptions

Jul 5th, 2000 10:03
Nathan Wallace, Hans Nowak, Snippet 342, Fredrik Lundh


"""
Packages: miscellaneous
"""
"""
> If I catch the exception like so:
> 
> try:
>   compile(file, "", "exec")
> except:
>   exception, msg, tb = sys.exc_info()
>   # look at traceback here
> 
> then I effectively lose where in the source file the exception
> occured.  If I examine the tb with the traceback module, I get
> something like this:
> 
>   File "./syntax_checker.py", line 36, in examine_files
>     compile(file, "", "exec")
>
> So I can do post-processing, check other files, and so on, which is
> nice, but I am not able to determine automatically where the problem is
> in the source file.  So, it's effectively useless.
oh, you're close.  the exception instance (msg
in your case) contains the information you're
looking for.  consider this little example:
"""
import sys, traceback
try:
    compile("""\
while 1:
    prnt 'foo'
""", "", "exec")
except SyntaxError:
    ev = sys.exc_info()[1]
    print ev, type(ev)
    for k, v in vars(ev).items():
        print k, "=", repr(v)
"""
which prints:
    filename = None
    lineno = 2
    args = ('invalid syntax', (None, 2, 14, "    prnt 'foo'\012"))
    offset = 14
    text = "    prnt 'foo'\012"
    msg = 'invalid syntax'
also see:
http://www.python.org/doc/current/lib/module-exceptions.html
"""