CxFreeze: Build Python Code to Executable

A key aspect of a programming language is building it into an executable/installer, which can be easily distributed. Since Python is more of a scripting language, the default Python installation doesn’t have any support for building executable. But due to its open source nature, there are multiple 3rd party packages available to fill this gap.

Earlier I have used Pyinstaller for building executable out of Python script. Few issues I encountered with PyInstaller was

  • False Virus Positives. This occurred in both single file build as well as folder build. I encountered this with Symantec antivirus but this issue seems more common. As per a github post, this is not not due no fault of PyInstaller and there seems to be little that can be done to overcome this annoying issue.
  • Ideally, I would like is a clean installation directory without too many files at the top level folder. PyInstaller supports single file option, but it would take some time to extract and run each time.

Cx Freeze definitely overcomes #2 above and I haven’t faced issue with #1 so far.

Installation

Download and install cx_Freeze:
Using pipenv:

pipenv install cx_Freeze

Or directly using pip:

pip install --upgrade cx_Freeze

Building Executable

Using In-built Script

If you just want to do a simple build, use the below command:

cxfreeze -c main.py --target-dir dist

where main.py is your main python file name and dist is the location where you want to do the build.

Using Custom Setup Script

In case if you want to customize your executable, like include additional files/folders, you can create a custom script for the build process. Lets assume that you have a folder called “Config” in your source code directory which you would like to include in your executable, then you can specify this using the “include_files” option as below.

import sys
from cx_Freeze import setup, Executable

build_exe_options = {
"packages": ["os"], 
"excludes": [""],
"include_files" : ["Config/"]
}

base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(
    name = "MyPythonApp",
    version = "0.1",
    description = "My Python Application!",
    options = {"build_exe": build_exe_options},
    executables = [Executable("main.py", base=base)]
)

To invoke the above setup script for building, use the below command:

python setup.py build

Building Installer

In Windows, you can build an installer out of the above executable using the below command:

python setup.py bdist_msi

References

  1. For more example setup scripts, refer to https://github.com/marcelotduarte/cx_Freeze/tree/main/cx_Freeze/samples

No comments:

Feel free to leave a piece of your mind.

Powered by Blogger.