[Chicago] exec saved compiled code

Cosmin Stejerean cstejerean at gmail.com
Wed Aug 29 09:28:33 CEST 2007

I'm not sure if I understand what's going on with the environment = {} part
so I'm not sure if my solution to your problem is correct but here is what I
think is wrong. As far as I can tell exec can take either a string or a code
object. exec(open('a.py','r').read()) works because you are reading the code
from a file (it could have been any other file extension) and exec is
parsing it.

exec(open('a.pyc','r').read()) this however reads the bytecode as a string
and passes it to exec. This is probably not what you want (and most likely
won't work). One solution is to simply import a, but I'm guessing that's not
what you want either. The other option is to not use py_compile but use the
compile function and pickle as follows

c = compile("print x", '<string>', 'exec')

now you have a code object that you can execute


If you pickle this code object to a file you will be able to read it and run
it (then again why not pickle the original string??). The problem is pickle
won't pickle code objects. But apparently you can use a little trick around
that (see

Is this at least close to what you were looking for?

- Cosmin

On 8/29/07, Massimo Di Pierro <mdipierro at cti.depaul.edu> wrote:
> Hello,
> I am hoping one of you can help me with this.
> environment={'x':3}
> open('a.py','w').write('print x')
> import py_compile,os
> exec(open('a.py','r').read()) in environment ### prints 3 OK!
> py_compile.compile(' a.py')
> os.unlink('a.py')
> exec(open('a.pyc','r').read()) in environment ### does not work
> QUESTION: how do exec a.pyc into environment so that it prints 3? Is
> it possible to do it?
> Massimo
> _______________________________________________
> Chicago mailing list
> Chicago at python.org
> http://mail.python.org/mailman/listinfo/chicago
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/chicago/attachments/20070829/093cb5a1/attachment.htm 

More information about the Chicago mailing list