Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

generating byte code from compiler.parse output

0 views
Skip to first unread message

Chris Wright

unread,
Aug 7, 2003, 9:05:34 PM8/7/03
to
Is there a way to go from the AST output of compiler.paser to byte
code

i.e. in the example below, is there a way to compile m and get a code
object that could then be called?

cheers and thanks for the help

chris wright

>>> s = """
... def test(x):
... y = x + 1
... print x, y
... """
>>> m = compiler.parse(s)
>>> m
Module(None, Stmt([Function('test', ['x'], [], 0, None,
Stmt([Assign([AssName('y', 'OP_ASSIGN')], Add((Name('x'), Const(1)))),
Printnl([Name('x'), Name('y')], None)]))]))
>>>

Martin v. Löwis

unread,
Aug 8, 2003, 1:56:57 AM8/8/03
to
c...@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

Chris Wright

unread,
Aug 8, 2003, 7:05:55 AM8/8/03
to
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)

mar...@v.loewis.de (Martin v. Löwis) wrote in message news:<m3wudoa...@mira.informatik.hu-berlin.de>...

0 new messages