On Tue, 2006-12-26 at 11:15 -0800, [EMAIL PROTECTED] wrote: > Hi, > > It is possible to get bytecode from code object. > Reversely, is it possible to create code object from bytecode? > > ex. > ## python code (not a module) > pycode = '''\ > print "<ul>\n" > for item in items: > print "<li>%s</li>\n" % item > print "</ul>\n" > ''' > > ## compile it and get bytecode > code = compile(pycode, kind='exec') > bytecode = code.co_code > open('hoge.pyc', 'wb').write(bytecode) > > ## load bytecode and eval it > bytecode = open('hoge.pyc', 'rb').read() > code = create_code(bytecode) ## how to ????? > output = eval(code, globals, {'items': ['A', 'B', 'C']})
As Fredrik has said, you should use marshal to handle the writing and reading of the code object. I'd like to point out the following additional facts that may not be apparent to you: * Code objects come in two flavors: statements and expressions. * exec can execute a 'statement' flavored code object. * eval can evaluate an 'expression' flavored code object. * Your code snippet is a statement, actually, a suite of statements. You need to exec it, not eval it. * You seem to think that eval'ing or exec'ing a code object will magically capture its output stream. It won't. What do you actually want to accomplish? Instead of having us poke at your first attempt at a solution, it might be more helpful if you told us what problem you're actually trying to solve. -Carsten -- http://mail.python.org/mailman/listinfo/python-list