Google Groepen ondersteunt geen nieuwe Usenet-berichten of -abonnementen meer. Historische content blijft zichtbaar.

generating byte code from compiler.parse output

0 weergaven
Naar het eerste ongelezen bericht

Chris Wright

ongelezen,
7 aug 2003, 21:05:3407-08-2003
aan
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

ongelezen,
8 aug 2003, 01:56:5708-08-2003
aan
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

ongelezen,
8 aug 2003, 07:05:5508-08-2003
aan
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 nieuwe berichten