[FRPythoneers] compile() and syntax errors

Jeffery D. Collins jcollins at boulder.net
Fri Aug 9 12:20:19 MDT 2002

This behavior is also the same for syntax errors in a module.  Take a 
look a sys.exc_info().  It contains lots of information related to the 
exception when accessed from the except: block.  The following is not 
well tested and may not work in general, but serves as an example of 
where you might look for a more robust solution:

s = """
def foo():
    print x

import sys

def my_compile(s, filename, kind):
    co = None
        co = compile(s, filename, kind)
    except SyntaxError:
        c, i, tb = sys.exc_info()
        i.filename = filename
        raise i
    return co
co = my_compile(s, "SOME FILE", "exec")


Mike Romberg wrote:

>  Since there are so many bright folks here on this list, I'd thought
>I'd try asking my question here first.  I'm importing modules by using
>pythons builting compile() command to get code objects.  These code
>objects can then be loaded into modules.  This is all integrated in
>with the imputil module.  But this problem is not really directly
>related to imputil.  Say I have some code like this:
>str = """
>def foo():
>    print 'hello'
>      error
>codeobj = compile(str, "fakemod", 'exec')
>  I've put in a deliberate syntax error in the code found in the
>string.  So... I get a traceback like this:
>Traceback (most recent call last):
>  File "test.py", line 7, in ?
>    codeobj = compile(str, "internal", 'exec')
>  File "<string>", line 4
>    error
>    ^
>SyntaxError: invalid syntax
>  What I'd really, really like is to not have the "<string>" show up
>as the module name.  It seems to me that it should use the filename
>argument I provided (internal).  If I could change <string> to
>something more informative, it would help identify exactly where
>errors occur (since I have many, many strings).  Perhaps there is some
>way to catch the error, hack the traceback and then rethrow the
>exception?  Anyone have an idea?
>Mike Romberg (romberg at fsl.noaa.gov)
>This message sent by the FRPythoneers mailing list.
>Unsubscribe: echo unsubscribe | FRPythoneers-request at lists.community.tummy.com
>URL: http://lists.community.tummy.com/mailman/listinfo/frpythoneers

More information about the FRPythoneers mailing list