Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to compile a program written in Python? [closed]

I am new to the Python programming language. I was wondering if it is possible to compile a program to written in Python.

Is it possible to convert Python scripts to some lower level programming languages which then can be compiled to binary code?

A developer who is considering to code in Python might want to keep the possibility open to be able to go for binary distribution later.

like image 336
bjh Hans Avatar asked Dec 24 '09 06:12

bjh Hans


People also ask

What happens when we compile a Python program?

Python first compiles your source code (. py file) into a format known as byte code . Compilation is simply a translation step, and byte code is a lower-level, and platform-independent, representation of your source code. Compiled code is usually stored in .

How can I protect my Python code but still make it available to run?

Instead of converting some parts of the code to C, they hide the entire python code inside a protective C layer. Then, if they want a module importable by python, they write a thin python extension on top of the C. Open source is a much easier way of life.

Do you need to compile a Python program?

Python does not need a compiler because it relies on an application (called an interpreter) that compiles and runs the code without storing the machine code being created in a form that you can easily access or distribute.


2 Answers

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 itself.

like image 72
Andrew Hare Avatar answered Oct 24 '22 22:10

Andrew Hare


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.

like image 21
carl Avatar answered Oct 24 '22 22:10

carl