Creating Executable Files from Python Scripts with py2exe

Creating Executable Files from Python Scripts with py2exe

Introduction

Executing Python scripts requires a lot of prerequisites like having Python installed, having a plethora of modules installed, using the command line, etc. while executing an .exe file is very straightforward.

If you want to create a simple application and distribute it to lots of users, writing it as a short Python script is not difficult, but assumes that the users know how to run the script and have Python already installed on their machine.

Examples like this show that there is a valid reason to convert .py programs into equivalent .exe programs on Windows. .exe stands for "Executable File", which is also known as a Binary.

The most popular way to achieve this is by using the py2exe module. In this article, we'll quickly go through the basics of py2exe and troubleshoot some common issues. To follow along, no advanced Python knowledge is needed, however you will have to use Windows.

Converting an interpreted language code into an executable file is a practice commonly called freezing.

Installing py2exe

To use the py2exe module, we'll need to install it. Let's do so with pip:

$ pip install py2exe

Converting Python Script to .exe

First, let's write up a a program that's going to print some text to the console:

import math
print("Hannibal ante Portas")
print(factorial(4))

Let's run the following commands in the Windows command line to make a directory (exampDir), move the code we already wrote to said directory, and finally, execute it:

$ mkdir exampDir
$ move example.py exampDir
$ cd exampDir
$ py example.py

This should output:

Hannibal ante Portas
24

Always test out the scripts before turning them into executables to make sure that if there is an error, it isn't caused by the source code.

Setup and Configuration

Make another file called setup.py in the same folder. Here we will keep configuration details on how we want to compile our program. We'll just put a couple of lines of code into it for now:

from distutils.core import setup # Need this to handle modules
import py2exe 
import math # We have to import all modules used in our program

setup(console=['example.py']) # Calls setup function to indicate that we're dealing with a single console application

If we were dealing with an app with a graphical UI, we would replace console with windows like so:

setup(windows=['example.py'])

Now open Command Prompt as administrator and navigate to the directory we just mentioned and run the setup.py file:

$ cd exampDir
$ python setup.py py2exe

running py2exe
*** searching for required modules ***
*** parsing results ***
...

dist folder

If all is done correctly, this should produce a subdirectory called dist. Inside it, there will be a few different files depending on your program, and one of them should be example.exe. To execute it from the console run:

$ example

And you'll be greeted by our Latin quote, followed by the value of 4!:

Hannibal ante Portas
24

Or, you can double click it and it'll run in the console.

If you'd like to bundle up all the files, add bundle_files and compressed, and set zipfile to None like so:

from distutils.core import setup
import py2exe

setup(
    options = {'py2exe': {'bundle_files': 1, 'compressed': True}},
    console = [{'script': "example.py"}],
    zipfile = None,
)

And re-run the commands to generate the .exe file.

Now, your end-users can run your scripts without any knowledge or prerequisites installed on their local machines.

Troubleshooting

Errors while converting .py files to .exe files are common, so we'll list some common bugs and solutions.

How to Fix Missing DLL-s After Using py2exe

A common issue with py2exe is missing .dll-s.

DLL stands for "dynamic-link library", and they're not there just to make bugs, promise. DLLs contain code, data, and resources which our program might need during execution.

After running the .exe, if you get a system error that says something like:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

The program can't start because something.dll is missing from your computer. Try reinstalling the program to fix this problem. 

Or the command line says:

ImportError: (DLL load failed: The specified module could not be found.)

The solution is to find the missing .dll and past it into your dist folder. There are two ways to do this.

  1. Search your computer for the file and then copy it. This will work most of the time.
  2. Find the missing .dll online and download it. Try not to download it from some shady website.

How to Generate 32/64-bit Executables Using py2exe?

To make a 64-bit executable, install 64 bit Python on your device. The same goes for the 32-bit version.

How to use py2exe on Linux or Mac

py2exe doesn't support on Linux or Mac, as it's aimed to create .exe files which is a Windows-unique format. You can download a Windows virtual machine on both Mac and Linux, use Wine or use a different tool like Pyinstaller on Linux, or py2app on Mac.

Conclusion

To make Python projects easier to run on Windows devices, we need to generate an executable file. We can use many different tools, like Pyinstaller, auto-py-to-exe, cx_Freeze, and py2exe.

Binary files may use DLL-s, so make sure to include them with your project.

Last Updated: December 4th, 2020
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Kristina PopovicAuthor

CS student with a passion for juggling and math.

Project

Building Your First Convolutional Neural Network With Keras

# python# artificial intelligence# machine learning# tensorflow

Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

David Landup
David Landup
Details
Course

Data Visualization in Python with Matplotlib and Pandas

# python# pandas# matplotlib

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

David Landup
David Landup
Details

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms