python compiled code ofuscation

Alex Martelli alex at magenta.com
Tue Aug 1 17:09:35 EDT 2000


"Jesus Cea Avion" <jcea at argo.es> wrote in message
news:3987141A.F6B6C132 at argo.es...
> > The first argument to exec can be a string or a compile'd string.
>
> You can really use compiled strings?   :-?

Yes, but not the way you're doing it...: 6.13 in the
Language Reference manual says "The first expression should
evaluate to either a string, an open file object, or a code
object".

> >>> import new
> >>> a=open("gestor_cache.pyc").read()
> >>> modname=new.module("gestor_cache")
> >>> modname
> <module 'gestor_cache' (built-in)>
> >>> exec(a,modname.__dict__)
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
> ValueError: embedded '\0' in exec string

Code objects are what is returned from the builtin compile
function; from the Library Reference:

compile (string, filename, kind)
Compile the string into a code object. Code objects can be executed by an
exec statement or evaluated by a call to eval(). The filename argument
should give the file from which the code was read; pass e.g. '<string>' if
it wasn't read from a file. The kind argument specifies what kind of code
must be compiled; it can be 'exec' if string consists of a sequence of
statements, 'eval' if it consists of a single expression, or 'single' if it
consists of a single interactive statement (in the latter case, expression
statements that evaluate to something else than None will printed).

[I guess the last words are meant to be "will BE printed"...].

So, for example:

>>> code=compile('print "ciao"', '<guess!>', 'exec')
>>> exec code
ciao
>>>

The advantage wrt an exec of the string is presumably one of performance:
the
string doesn't have to be reparsed and bytecompiled every time if it's
subject
to exec over and over.


Alex







More information about the Python-list mailing list