Q: How to generate code object from bytecode?

Fredrik Lundh fredrik at pythonware.com
Tue Dec 26 14:31:46 EST 2006


kwatch at gmail.com wrote:

> 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']})

use the marshal module; see the last script on this page for an example:

     http://effbot.org/librarybook/marshal

</F>




More information about the Python-list mailing list