generating byte code from compiler.parse output

Chris Wright caw at cs.mu.oz.au
Fri Aug 8 13:05:55 CEST 2003


After Martin's gentle prodding, I came up with the code below
(without error checking etc....)

I am very grateful !

cheers

Chris

------------------

from compiler import parse, syntax
from misc import set_filename
from pycodegen import ModuleCodeGenerator

class Test:
    def __init__(self):
        pass

def munge_code_string(s):
    m = parse(s)
    set_filename("<string>", m)
    syntax.check(m)
    print m
    gen = ModuleCodeGenerator(m)
    c = gen.getCode()
    return c


code_string = """
def f(x):
    print x
"""

if __name__ == '__main__':
    t = Test()
    code = munge_code_string(code_string)
    exec code in globals(), t.__dict__
    print dir(t)
    t.f(4)

martin at v.loewis.de (Martin v. Löwis) wrote in message news:<m3wudoadzq.fsf at mira.informatik.hu-berlin.de>...
> caw at cs.mu.oz.au (Chris Wright) writes:
> 
> > Is there a way to go from the AST output of compiler.paser to byte
> > code
> 
> Yes. Use the source, Luke.
> 
> > i.e. in the example below, is there a way to compile m and get a code
> > object that could then be called?
> 
> You have to find out what compiler.compile is doing in addition to
> what you are doing. Then, you find, that you need misc.set_filename,
> syntax.check, ModuleCodeGenerator, and .getCode, in that order.
> 
> HTH,
> Martin




More information about the Python-list mailing list