Create an executable file with Python

python_exe

In this post I’m going to show how to create and executable file using Python. Imagine that you have written a nice program and you want to share it with more people but these people don’t have Python installed. You can tell all of them how to install Python in their computers, but it takes time. Easier, you can create an executable file that is ready to be used in Windows.

Step 0. What you should have already installed:
Python 2.7 installed with VPython. You can use any IDE, to make thing easy I’m going to stick with the one I used in all my posts.

Step 1. Install py2exe:
Download py2exe from SourceForge. Remember to choose the file for Python 2.7 and for Windows 32-bits. First thing to do once you have downloaded the py2exe file is to run it and wait for the installation to finish. Check that it finds the Python installation (it should be found automatically). Once it is finished, open VIDLE for VPyhton.

Step 2. Python code:
First, we create a program that opens a small window with the message “Welcome to py2exe!”. This will be very handy in the future for applications that require inputs from the user. The library that handles the graphical user interface (GUI) is called TkInter. This library is already installed by default with your Python 2.7 so you already have it. Just create the following code and save it with the name gui_example.py:

If you run this program with VIDLE, you will see something like this (the window you just created is inside the orange box in the image):

Pop up windows created with TkInter
Pop up windows created with TkInter

Now we have to build the executable with py2exe. Open a different Python script and write the following code and save it as setup.py:

That’s all, as you can see, you just import the required libraries and called the file you created earlier. We need to run this code with py2exe to generate or executable file. To do this you have to open a command prompt in Windows and write:
python setup.py py2exe
And now wait for the program to finish, it will take some time to generate your executable. When finished, explore the folder where you have your original file and you will see two folders. Inside ‘dist’ folder, you’ll find something like this:

Files after running the second Python file
Files after running the second Python file

If you double-click gui_example.exe, you will get the same result as when you ran the Python script.

Leave a Reply