Q: How to generate code object from bytecode?

Carsten Haese carsten at uniqsys.com
Tue Dec 26 14:48:59 EST 2006


On Tue, 2006-12-26 at 11:15 -0800, kwatch at gmail.com 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





More information about the Python-list mailing list