Python code persistance

Andre Michel Descombes amdescombes at qualicontrol.com
Thu Aug 29 17:41:52 CEST 2002


Thanks Andrés,

I will take a look! It looks very promising.

Andre

"Andrés" <ahindra at hotmail.com> wrote in message
news:5cc917de.0208281644.3aa518a3 at posting.google.com...
> I posted a reply earlier but maybe it got lost or its just delayed,
> anyways I improved the code. Note that pickle or marshall don't
> support persistence of code objects . the py_compile.compile may also
> work but it works with files only and not strings.
>
>
> import new
> import pickle
>
> #the string with code
> mycode = "a =2+2\nprint a"
>
> #the built-in compile() function converts it to
> #a code object (compiles it)
>
> mycodeobj = compile (mycode,'<string>','exec')
>
>
> #a tuple is made storing all the code object properties needed
> #for new.code()
>
> codetup =
(mycodeobj.co_argcount,mycodeobj.co_nlocals,mycodeobj.co_stacksize,
> mycodeobj.co_flags,
mycodeobj.co_code,mycodeobj.co_consts,mycodeobj.co_names,
> mycodeobj.co_varnames,mycodeobj.co_filename,
> mycodeobj.co_name,mycodeobj.co_firstlineno,mycodeobj.co_lnotab)
>
> #the tuple is dumped into a string or file (string in this case)
>
> codedump = pickle.dumps(codetup)
>
> #at this point the codedump variable is a string
> #so it can be stored in a database
> #and then retrieved like:
>
> coderecover = pickle.loads(codedump)
>
> #now the new.code() function is used, the retrieved tuple contains all
> information
> #to build the code object
>
> reconstructed = new.code
>
(coderecover[0],coderecover[1],coderecover[2],coderecover[3],coderecover[4],
coderecover[5],coderecover[6],
>
coderecover[7],coderecover[8],coderecover[9],coderecover[10],coderecover[11]
)
>
> #...
>
> exec (reconstructed)





More information about the Python-list mailing list