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)]))]))
>>>
> 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
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>...