compilation – Is it possible to compile a program written in Python?

compilation – Is it possible to compile a program written in Python?

I think Compiling Python Code would be a good place to start:

Python source code is automatically
compiled into Python byte code by the
CPython interpreter. Compiled code is
usually stored in PYC (or PYO) files,
and is regenerated when the source is
updated, or when otherwise necessary.

To distribute a program to people who
already have Python installed, you can
ship either the PY files or the PYC
files. In recent versions, you can
also create a ZIP archive containing
PY or PYC files, and use a small
“bootstrap script” to add that ZIP
archive to the path.

To “compile” a Python program into an
executable, use a bundling tool, such
as Gordon McMillan’s installer
(alternative download)
(cross-platform), Thomas Heller’s
py2exe (Windows), Anthony Tuininga’s
cx_Freeze (cross-platform), or Bob
Ippolito’s py2app (Mac). These tools
puts your modules and data files in
some kind of archive file, and creates
an executable that automatically sets
things up so that modules are imported
from that archive. Some tools can
embed the archive in the executable

If you really want, you could always compile with Cython. This will generate C code, which you can then compile with any C compiler such as GCC.

compilation – Is it possible to compile a program written in Python?

Python, as a dynamic language, cannot be compiled into machine code statically, like C or COBOL can. Youll always need an interpreter to execute the code, which, by definition in the language, is a dynamic operation.

You can translate source code in bytecode, which is just an intermediate process that the interpreter does to speed up the load of the code, It converts text files, with comments, blank spaces, words like if, def, in, etc in binary code, but the operations behind are exactly the same, in Python, not in machine code or any other language. This is what its stored in .pyc files and its also portable between architectures.

Probably what you need its not compile the code (which its not possible) but to embed an interpreter (in the right architecture) with the code to allow running the code without an external installation of the interpreter. To do that, you can use all those tools like py2exe or cx_Freeze.

Maybe Im being a little pedantic on this 😛

Leave a Reply

Your email address will not be published. Required fields are marked *