Packaging Python Code

When modules are imported in Python by other modules, Python compiles the relevant code into byte-code, an intermediate, portable, closer-to-low-level binary language form. This byte-code is stored with the .pyc suffix, short for Python compiled, instead of the typical .py.

Python's .pyc files correspond roughly to DLLs (dynamically loaded libraries) used in C. Regular .py modules can be used dynamically, too, but the compiled Python code is tighter and Python interprets the code at runtime when the file is imported.

Precompiling scripts is one way to speed up Python programs that need to import many modules. You can minimize a program's startup time by making sure source code is kept in directories where Python will have access to writing .pyc files.

You can also ship Python programs as .pyc files rather than as .py scripts. Since .pyc files are binary, they cannot be run as scripts, but they can be sent to the Python interpreter; simply add the name of the .pyc file the next time you run Python, like this:

Python runme.pyc

In order to build a compiled Python file from the Python interpreter, import the compile function from py_compile and run the compile command, like this:

from py compile import compile compile("script to compile.py")

Was this article helpful?

0 0

Post a comment