14 Jan 2023

Compiling and Packaging Python Applications into Single Binary

One of the needs for any software is a way to distribute your system in a single package. I will provide a general guide on how to use Nuitka to build a python binary.

Integrating Nuitka with your code.

We will use the library Nuitka. Nuitka is a Python compiler that allows us to achieve the single binary goal.

  1. Create an entrypoint for the Nuitka.

    from sample_python_binary.run import main
    if __name__ == '__main__':
        main()
    
  2. Run the following command to build the package

    time env/bin/python -m nuitka \
            --onefile \
            --include-data-files=data_dir/ml_model.txt=data_dir/ \
            --include-data-files=data_dir/sample_license=data_dir/ \
            --include-module=sqlalchemy.sql.default_comparator \
            --include-module=sqlalchemy.dialects \
            --linux-onefile-icon=data_dir/python3.xpm \
            sample_binary.py # the entrypoint you have created earlier
    

Build Dependency Options

  1. Data files: data files are like needed configs required by your program like ML models or some text files that you need for import.
  2. Module files: module files are the other dependency of your program. Nuitka does a good job of integrating your other python dependencies but sometimes these dependencies have an obscure way of import, this is where the option of importing module files.
  3. Linux Onefile icon: if you have a custom icon that you want to represent your program with.

Once you have run the program above you will now have compiled version of your python application.

Issues

As mentioned, Nuitka does a good job of compiling your application but it has some nuances that you need to look out for.

  • System dependencies: you will still need to install the system dependencies of your program. This is where containerization comes in.
  • Compiling platform: Nuitka is not platform agnostic meaning you will need to compile your code from the target platform e.g. If the target platform is linux you need to compile in linux.

Tags: