Comprehensive Guide to Compiling Python to Executable with Nuitka

O

Ohidur Rahman Bappy

MAR 22, 2025

Nuitka: Compiling Python to Executable

Nuitka is a Python compiler, serving as a seamless replacement for the standard Python interpreter. It compiles every construct available in CPython for versions 2.6 through 3.8.

Getting Started

  1. Install Nuitka

    pip install nuitka
    
  2. Prepare a Project Folder

    mkdir HelloWorld
    cd HelloWorld
    
  3. Create a Python Script

    Create a file named hello.py:

    def talk(message):
        return "Talk " + message
    
    def main():
        print(talk("Hello World"))
    
    if __name__ == "__main__":
        main()
    
  4. Run the Script

    python hello.py
    
  5. Compile the Script with Nuitka

    python -m nuitka --mingw64 hello.py
    

    This will generate hello.exe, which can be executed directly.

Use Cases

Program Compilation with Embedded Modules

To compile a complete program recursively, use:

python -m nuitka --follow-imports program.py

Additional options like --include-plugin-directory=plugin_dir can include specific directories in the executable if needed.

Extension Module Compilation

Compile a single extension module with:

python -m nuitka --module some_module.py

This results in some_module.so which can replace some_module.py.

Package Compilation

Compile a full package by embedding all modules:

python -m nuitka --module some_package --include-package=some_package

Common Challenges

Dynamic sys.path

Scripts modifying sys.path may not compile correctly. Setting PYTHONPATH during compilation can help.

Tips for Effective Usage

Python Command Line Flags

To pass flags like -O or -S, use --python-flag=.

Caching and Compilation Speed

Install ccache for faster repeated compilations:

  • On Linux: Ensure ccache is in PATH
  • On Windows: Use ccache.exe, which Nuitka can download automatically

Running Nuitka

Always run Nuitka via:

python -m nuitka

This ensures compatibility between Nuitka and the Python version.

Recommended C Compilers

  • Windows: MinGW64 is faster than MSVC
  • Linux: clang6 provides slight performance improvements over gcc-6.3

Standalone Executables and Dependencies

For creating standalone executables on Windows, using:

python -m nuitka --standalone --windows-dependency-tool=pefile myprogram.py

This avoids unnecessary dependencies and speeds up compilation.

Handling Windows Errors

Exclude your compilation stages from Windows Defender and Indexing to prevent errors due to locked files.

Redistribution of Standalone Programs

Ensure the installation of Visual C Runtime libraries on older Windows versions to address dependency issues.

Refer to Nuitka's official documentation for more detailed instructions and advanced use cases.