Python code persistance
Andrés
ahindra at hotmail.com
Wed Aug 28 17:40:58 EDT 2002
"Andre Michel Descombes" <amdescombes at qualicontrol.com> wrote in message news:<akimoh$jh7$1 at wanadoo.fr>...
> Hi,
>
> I am using PythonForDelphi to execute some dynamic code coming from a string
> using the Exec function. The problem I have, is this string can be quite
> long and it takes quite a while to compile it everytime in order to call the
> several functions defined within it. Is it at all possible to persist this
> compiled code to disk or database in order to be able to just load it
> (without having to recompile it) the next time the program is run? I don't
> want to save it to a .py file if it can be avoided.
>
> Thanks for your help,
>
> Andre M. Descombes
import new
#the string with code
mycode = "print 'hello'\nprint 'world'"
#the built-in compile() function converts it to
#a code object (compiles it)
mycodeobj = compile (mycode,'<string>','exec')
#all the following are the code object properties and can be stored in a database
#, the tuple type can be pickled using the pickle or cpickle modules
arguments = mycodeobj.co_argcount
nlocals = mycodeobj.co_nlocals
stacksize = mycodeobj.co_stacksize
flags = mycodeobj.co_flags
codestring = mycodeobj.co_code
constants = mycodeobj.co_consts
names = mycodeobj.co_names
varnames = mycodeobj.co_varnames
file = mycodeobj.co_filename
name = mycodeobj.co_name
firstlineno = mycodeobj.co_firstlineno
lnotab = mycodeobj.co_lnotab
#with the new.code function the code object can be built
reconstructed = new.code (arguments,nlocals,stacksize,flags,
codestring,constants,names,varnames,file,name,firstlineno,lnotab)
exec (reconstructed)
More information about the Python-list
mailing list