Hi! Hope you're enjoying this blog. I have a new home at www.goldsborough.me. Be sure to also check by there for new posts <3

Friday, July 12, 2013

Tutorial: How to compile a Python program

Have you ever wanted to show your Python programs to somebody else without them having to download Python? Well, welcome to the world of compiling! There are a couple libraries for creating stand-alone executables for Python, although I have only ever used one called cx_Freeze.

It works really well, is super simple and gets regular updates so you won't have a problem finding the right version for your Python (Note: it is essential that the cx_freeze version you download is the same as your Python version, or installation won't work.). So if you haven't yet, download and install cx_freeze.

Next, write a simple program that we'll then compile later on. For example:

print("Hello World!")

and save it as "hello.py" to your desktop.

Now all we need is a setup file which cx_freeze can then execute:

from cx_Freeze import setup, Executable

        name = "hello",
        version = "0.1",
        description = "Sample cx_Freeze script",
        executables = [Executable("hello.py")])

You can find other examples for setup files in the "Samples" folder of the cx_freeze installation folder, for example an "advanced" one where you can include files the program needs, or one for compiling PyQt, although I'll also make a tutorial for that. Anyway, the above setup is all we need for now.

So save the code I have provided as setup.py and make sure it's in the same directory as the file you want to compile, in this case the desktop. Then, call your OS' command line and change directory (type cd) to your desktop. Now, simply type "setup.py build" (without quotation marks). It should look like this:

Hit enter and watch your file compile. You should get a "build" folder in your directory with the executable in it. Have fun sharing!

Any problems? Leave me a comment!

No comments :

Post a Comment