generating byte code from compiler.parse output

C

Chris Wright

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
.... def test(x):
.... y = x + 1
.... print x, y
.... """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)]))]))
 
M

Martin v. =?iso-8859-15?q?L=F6wis?=

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
 
C

Chris Wright

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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top