Need information om Python byte-code

Fredrik Lundh fredrik at pythonware.com
Tue Dec 14 03:18:40 EST 1999


Nick Maxwell <dotproduct at usa.net> wrote:
> I am currently writing MUD software with a server written in C++.  I have
> plans to embed Python into the server so it can act as the mud language.  I
> was reading the Python tutorials a while ago, and found that modules can be
> compiled into byte-code for faster compiling.  I have messed around with the
> compile function, but to no avail.  I have RTFM many times now on this
> subject, and I just can't get it.  If someone could just tell me the exact
> steps to compiling a module into byte-code, I would really appreciate it!

python always compiles everything to bytecode before
it executes it (and caches the result in .pyc files). you
don't have to do anything to get that behaviour...

if you insist on compiling things yourself, use the
"compile" (!) function:

    filename = "module.py"
    source = open(filename).read()
    code = compile(source, filename, "exec")
    exec code # run it

the marshal module allows you to serialize code
objects:

    data = marshal.dumps(code) # convert to string
    code = marshal.loads(data) # and back
    exec code # run it again

pyc files are simply serialized code objects, plus a small
header.  see the py_compile module for details.

</F>

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list