A person pulling a lever on a large machine that feeds a script through a hopper into a C compiler, which outputs packaged boxes stamped with the Python logo.

Nuitka: Compile Python Into a Standalone Executable

by Shanzia Shabnom Mithun Updated Reading time estimate 23m intermediate python tools

Nuitka is a Python compiler that turns your code into a native executable. Its distribution modes let you package an application to run on a compatible machine without a separate Python installation. A more common way to do this is to use a bundler like PyInstaller, which ships your application together with the Python runtime and its dependencies. Nuitka instead compiles your Python code to C before building the executable.

That distinction matters when you’re deciding how to distribute a Python application. Depending on your workload and build mode, Nuitka can offer performance benefits, but they come with trade-offs, including longer build times and additional compiler requirements.

By the end of this tutorial, you’ll understand that:

  • Nuitka compiles your Python code to C, while PyInstaller bundles your code with the Python interpreter.
  • --mode=standalone produces a folder, --mode=onefile produces a single file that starts more slowly, and --mode=app picks a platform-appropriate format.
  • Nuitka’s speedup depends on the workload, and CPU-bound code dominated by Python-level loops benefits the most.
  • Nuitka is worth considering when your own benchmarks show a speedup that justifies the C compiler dependency and longer build times.

In this tutorial, you’ll compile a small command-line tool and see where compiling pays off. To follow along, you should be comfortable running Python scripts from the terminal and using a virtual environment. You don’t need any experience with C. Nuitka drives the compiler for you.

Take the Quiz: Test your knowledge with our interactive “Nuitka: Compile Python Into a Standalone Executable” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

Nuitka: Compile Python Into a Standalone Executable

Test your understanding of compiling Python with Nuitka, from standalone and onefile builds to speedups and when PyInstaller fits better.

Getting Started With Nuitka

Before you compile your first Python application, you’ll need Nuitka and a supported C compiler. This tutorial uses Python 3.13.15 for the builds shown below. The compiler setup is discussed later in this section.

You can use uv to create an isolated environment and install Nuitka. If you don’t have uv installed, use the venv and pip alternative described after these steps. Create the environment with uv:

Language: Shell
$ uv venv --python 3.13.15

Activate the environment. On macOS and Linux, run the following command:

Language: Shell
$ source .venv/bin/activate

In Windows PowerShell, run the following command:

Language: Windows PowerShell
PS> .\.venv\Scripts\Activate.ps1

In the commands below, (.venv) indicates an activated Python virtual environment, whether you created it with venv, uv venv, or another tool.

Then install the version of Nuitka used for this tutorial:

Language: Shell
(.venv) $ uv pip install nuitka==4.2.1

Alternatively, create the environment with python -m venv .venv, activate it using the appropriate command above, and install Nuitka with python -m pip install nuitka==4.2.1. The rest of the tutorial uses python -m nuitka, so the build commands work the same way once the environment is activated.

Nuitka uses a C toolchain during compilation, and the compiler setup depends on your operating system. Check the official installation documentation for the current platform-specific requirements.

For this tutorial, you’ll use a small command-line program that counts the most common words in a text file. Save the following code as wordcount.py:

Language: Python Filename: wordcount.py
from argparse import ArgumentParser
from collections import Counter
from pathlib import Path

def main():
    parser = ArgumentParser(
        description="Show the most common words in a text file."
    )
    parser.add_argument("file", type=Path)
    parser.add_argument("-n", "--top", type=int, default=5)
    args = parser.parse_args()

    words = args.file.read_text(encoding="utf-8").lower().split()

    for word, count in Counter(words).most_common(args.top):
        print(f"{word}: {count}")

if __name__ == "__main__":
    main()

This script reads a text file, counts word frequency, and prints the most common entries.

Save the following text as sample.txt in the same directory:

Language: Text Filename: sample.txt
Python is popular because Python is easy to learn and easy to use.
Python is also popular for data science and automation.

You’ll use this short file as input throughout the tutorial.

Run the script normally first, before compiling anything:

Language: Shell
(.venv) $ python wordcount.py sample.txt -n 5

This prints the five most common words:

Language: Program Output
python: 3
is: 3
popular: 2
easy: 2
to: 2

With Nuitka installed and your script ready, you’re set to compile your code. Next, you’ll explore the build modes Nuitka offers and see how they differ.

Exploring Nuitka’s Build Modes

Nuitka supports several build modes, each controlling what it produces. This tutorial focuses on three modes useful for distributing applications: --mode=standalone, --mode=onefile, and --mode=app.

Nuitka also offers other modes, such as --mode=module and --mode=package, for compiling importable extensions rather than executables. Those are outside the scope of this tutorial but worth knowing about if you’re building a library.

With that setup covered, you can compile your first executable.

Building a Standalone Distribution

Standalone mode is the most direct way to distribute a compiled app: Nuitka compiles your script and collects everything it needs to run, including the Python runtime, into a single folder you can copy to a compatible machine.

From the directory containing wordcount.py and sample.txt, compile the script using --mode=standalone:

Language: Shell
(.venv) $ python -m nuitka --mode=standalone wordcount.py

This creates a wordcount.dist/ directory containing the compiled executable and the files it needs to run. On Windows, the executable is named wordcount.exe. On Linux and macOS, it’s named wordcount.bin.

On Windows, stay in the directory where you ran the build command and run:

Language: Windows PowerShell
PS> .\wordcount.dist\wordcount.exe sample.txt -n 5

On Linux and macOS, also stay in that directory and run the executable inside wordcount.dist/:

Language: Shell
(.venv) $ ./wordcount.dist/wordcount.bin sample.txt -n 5

You’ll get the same output as before:

Language: Program Output
python: 3
is: 3
popular: 2
easy: 2
to: 2

Unlike the original script, the compiled executable runs directly without python.

Building a Single Executable With Onefile

There’s also --mode=onefile, which takes the same source program and packages the resulting executable and its dependencies into a single file instead of a folder.

Compile wordcount.py again, this time with --mode=onefile:

Language: Shell
(.venv) $ python -m nuitka --mode=onefile wordcount.py

This first performs a standalone-style build and then packages that payload into the final onefile executable. Build directories such as wordcount.build, wordcount.dist, and wordcount.onefile-build can remain after compilation, but you only need to distribute the final wordcount.exe on Windows or wordcount.bin on Linux and macOS.

On Windows, run the onefile executable directly:

Language: Windows PowerShell
PS> .\wordcount.exe sample.txt -n 5

On Linux and macOS, run the onefile executable directly:

Language: Shell
(.venv) $ ./wordcount.bin sample.txt -n 5

The onefile executable produces the same word counts as the standalone build, so the two are indistinguishable by their output alone. The main differences are how they’re distributed and what happens during startup, which you’ll measure later in the tutorial.

Building With App Mode

If you’re building for multiple operating systems, --mode=app provides a platform-aware way to package your application. On Windows and Linux, it produces a onefile-style executable. On macOS, it creates an application bundle such as wordcount.app.

App mode doesn’t make the resulting build cross-platform: a Windows build still targets Windows, a Linux build targets Linux, and a macOS build targets macOS.

To try app mode, build the application with the following command:

Language: Shell
(.venv) $ python -m nuitka --mode=app --output-dir=app-build wordcount.py

This keeps the app-mode output in app-build/, separate from the onefile executable you’ll measure later.

If you specifically need the folder-based layout of a standalone distribution, use --mode=standalone instead.

Packaging a Standalone Executable

You’ve built the application in several modes. Now take a closer look at the standalone distribution: why does this mode produce a directory of files rather than just an executable?

To answer that, inspect the distribution’s contents and see why the compiled application still needs supporting files.

Understanding the Standalone Distribution Layout

On Windows, take a look inside the folder that was generated:

Language: Windows PowerShell
PS> Get-ChildItem .\wordcount.dist\

On Linux and macOS, use ls -l wordcount.dist/ instead.

You’ll find the compiled executable alongside the supporting files the application needs. Depending on your platform and the modules your application uses, these can include Python runtime libraries, extension modules, and system libraries.

On Windows, you’ll typically see files such as python313.dll, .pyd extension modules, and C runtime libraries like vcruntime140.dll. The exact contents of the distribution vary by platform, Python version, and application.

On Windows, the directory listing looks like this, shortened to show only the mode and filename columns:

Language: Program Output
Mode   Name
----   ----
-a---- python313.dll
-a---- select.pyd
-a---- unicodedata.pyd
-a---- vcruntime140.dll
-a---- vcruntime140_1.dll
-a---- wordcount.exe
-a---- _bz2.pyd
-a---- _lzma.pyd
-a---- _socket.pyd
-a---- _wmi.pyd

Compiling your code to C doesn’t remove its dependence on Python’s runtime. On this Windows build, the compiled application still uses the CPython library, python313.dll, for operations such as managing Python objects and memory. Your imports can also bring in other modules indirectly, and Nuitka includes additional components needed for standalone execution.

For example, this build’s compilation report lists _socket as an extension module needed for standalone mode, which explains why _socket.pyd appears even though wordcount.py never imports socket directly. To generate your own report, add --report=compilation-report.xml to the build command.

Linux builds have a different layout and use platform-specific shared libraries rather than Windows .dll and .pyd files. For example, a Linux build may include a libpython shared library alongside wordcount.bin. Don’t expect the Windows and Linux distribution folders to match file for file.

Understanding Why Dependencies Get Packaged This Way

A standalone executable can’t assume that the target machine has the same Python installation or dependencies as the machine where you built it. The build process, therefore, collects the components it determines the application needs and places them in the distribution directory.

This gives you a self-contained application that you can copy to a compatible machine and run without installing Python first. The trade-off is that you distribute a folder rather than a single file, and that folder can be considerably larger than your original Python script.

To see this in practice, copy the entire wordcount.dist folder to another location or a compatible machine. The executable depends on the other files packaged alongside it, so keep the folder’s contents together.

Note that sample.txt isn’t part of the distribution. It’s input to the program, so whoever runs the tool passes the path to their own text file. For example, suppose you copy wordcount.dist to C:\Tools on Windows. You can then run the executable from another directory using the command below, replacing C:\Users\me\notes.txt with the path to an existing text file:

Language: Windows PowerShell
PS> C:\Tools\wordcount.dist\wordcount.exe C:\Users\me\notes.txt -n 3

Running the copied executable this way checks that it can find its supporting files outside the original development folder.

Measuring Performance Trade-Offs

Distribution format is one part of the story. The other is runtime performance. Next, you’ll compare distribution size and startup overhead, then measure whether compilation speeds up a CPU-bound workload.

For the timing benchmarks below, each configuration was run five times on the Windows machine described earlier, and the reported value is the median rather than a single run.

Comparing Distribution Size

For wordcount.py, the Windows builds had these sizes:

Build What You Distribute Size
Standalone Folder with 10 files ~12.7 MB
Onefile Single executable ~4.26 MB
App on Windows Single executable ~4.27 MB

In this test, the onefile executable is roughly a third the size of the standalone distribution because its bundled payload is compressed.

The exact size difference depends on the platform, Python installation, application dependencies, and compression settings. In particular, you shouldn’t assume that a onefile build will have the same size relationship to a standalone distribution on every system.

Comparing Startup Time

By default, the onefile build has additional startup overhead because it has to unpack its payload to a temporary location before the application can start. You can compare the standalone and onefile builds using PowerShell’s Measure-Command on Windows or time on Linux and macOS.

First, measure the standalone build. On Windows, run:

Language: Windows PowerShell
PS> Measure-Command { .\wordcount.dist\wordcount.exe sample.txt -n 5 }

On Linux and macOS, run:

Language: Shell
$ time ./wordcount.dist/wordcount.bin sample.txt -n 5

For the time commands, compare the elapsed wall-clock time, typically labeled real in Bash or total in Zsh.

Now measure the onefile build. On Windows, run:

Language: Windows PowerShell
PS> Measure-Command { .\wordcount.exe sample.txt -n 5 }

On Linux and macOS, run:

Language: Shell
$ time ./wordcount.bin sample.txt -n 5

These commands measure the entire run, including startup, reading the input file, counting words, and printing the results. Because the input contains only two lines, the workload is small, making total runtime a useful approximation for comparing startup overhead.

Across five alternating runs on the Windows machine described earlier, the results were:

Build Median Total Runtime
Standalone 49.68 ms
Onefile 349.68 ms

In this test, the onefile executable took about seven times as long to complete the run as the standalone executable. That gap comes from the unpacking step, and the ratio will vary on other machines.

For a short-lived command-line tool like wordcount.py, that extra startup time is easy to notice. But if you’re distributing an application as a single download, onefile’s simplicity can make the trade-off worthwhile.

On the other hand, if an application launches frequently, such as a utility invoked repeatedly by a script or CI pipeline, the standalone folder avoids the repeated unpacking step and starts faster each time.

Measuring a CPU-Bound Benchmark

To explore whether compilation can reduce Python-level execution overhead, use a CPU-bound workload with plenty of loops, function calls, arithmetic, and comparisons. Counting prime numbers with simple trial division provides a straightforward example:

Language: Python Filename: cpu_benchmark.py
import time

def is_prime(number):
    if number < 2:
        return False

    for divisor in range(2, number):
        if number % divisor == 0:
            return False

    return True

def main():
    start = time.perf_counter()

    count = 0
    for number in range(2, 100_000):
        if is_prime(number):
            count += 1

    elapsed = time.perf_counter() - start

    print(f"Primes found: {count}")
    print(f"Time: {elapsed:.3f}s")

if __name__ == "__main__":
    main()

Run the benchmark first with the regular Python interpreter. The script uses time.perf_counter() to measure the workload internally, so you don’t need an external timing command.

On Windows, run:

Language: Windows PowerShell
(.venv) PS> python cpu_benchmark.py

On Linux and macOS, run:

Language: Shell
(.venv) $ python cpu_benchmark.py

The script reports the number of primes found along with the elapsed time:

Language: Program Output
Primes found: 9592
Time: 16.395s

This is one representative run. Your elapsed time may differ.

Next, compile the script in standalone mode and run the resulting executable. On Windows, run the following commands:

Language: Windows PowerShell
(.venv) PS> python -m nuitka --mode=standalone cpu_benchmark.py
(.venv) PS> .\cpu_benchmark.dist\cpu_benchmark.exe

On Linux and macOS, the executable has a .bin extension:

Language: Shell
(.venv) $ python -m nuitka --mode=standalone cpu_benchmark.py
(.venv) $ ./cpu_benchmark.dist/cpu_benchmark.bin

Then compile the same script in onefile mode and run the single executable. On Windows, run the following commands:

Language: Windows PowerShell
(.venv) PS> python -m nuitka --mode=onefile cpu_benchmark.py
(.venv) PS> .\cpu_benchmark.exe

On Linux and macOS, run:

Language: Shell
(.venv) $ python -m nuitka --mode=onefile cpu_benchmark.py
(.venv) $ ./cpu_benchmark.bin

Each configuration produces the same result: Primes found: 9592. The elapsed time will vary between runs and machines. The comparison below shows the median elapsed time across five runs of each configuration.

Interpreting the Results

Here’s how the three approaches compare on this benchmark:

Build Median Time
Regular Python 16.471 s
Standalone 11.082 s
Onefile 10.849 s

In this benchmark, the standalone median was about 1.49 times as fast as the regular Python baseline, while the onefile median was about 1.52 times as fast. Don’t take those ratios as a given, though. The same script on a different machine may show little or no improvement, or a different speedup, depending on the CPU, interpreter build, and system environment.

Unlike the startup-time comparison earlier, standalone and onefile perform almost identically here. The time.perf_counter() measurement starts after the executable has already launched, so it doesn’t capture the onefile unpacking overhead you measured earlier. That unpacking happens during startup and isn’t part of the timed workload in this benchmark.

The timeline below puts both measurements side by side. In the wordcount.py view, the onefile lane’s extra time is the difference between the two medians, about 300 ms spent before your code starts. Switch to cpu_benchmark.py to see why time.perf_counter() doesn’t capture it:

Interactive diagram — enable JavaScript to view.

Run-to-run variation from background system activity and CPU scheduling can also affect results like these, which is why the comparison uses medians.

This kind of speedup is workload-dependent. A tight loop dominated by Python-level dispatch, like the prime-counting loop above, gives compilation room to reduce interpreter overhead. Code that spends most of its time waiting on I/O, network calls, or already-optimized C extensions, like math.sqrt(), may see a much smaller improvement because the interpreter accounts for less of its runtime.

PyInstaller, by contrast, doesn’t compile your Python code. It bundles the Python interpreter and your application, so you shouldn’t expect the same kind of runtime performance change from packaging your code with it.

Choosing Between Nuitka and PyInstaller

Here’s how Nuitka and PyInstaller compare for common distribution needs:

Use Case Pick Nuitka Pick PyInstaller
CPU-bound Python code where runtime speed matters ✅ —
Discouraging casual inspection of your source code ✅ —
A quick bundle without setting up a C compiler — ✅

Nuitka’s compilation approach can be particularly useful when runtime performance matters, but the benefit depends on the workload, as you saw in the benchmark above. PyInstaller only packages your code, so it doesn’t offer this kind of runtime optimization.

Nuitka can also make casual inspection of your application code more difficult because it compiles Python modules rather than distributing them in the same form as a typical bundled Python application. This isn’t the same as strong code protection, and determined reverse engineering is still possible. Still, making your code harder to inspect may matter when you’re distributing commercial, closed-source software.

Both tools can produce a single-file executable, so that requirement alone isn’t a reason to choose Nuitka over PyInstaller. The more meaningful differences come down to whether you want compilation, whether you can accommodate a C compiler in your build process, and whether you can benefit from Nuitka’s workload-dependent performance characteristics.

If Nuitka looks like a good fit, it’s worth understanding the trade-offs that come with choosing it.

Understanding Nuitka’s Limitations

The benefits above come with real costs, and it’s worth knowing them before you commit to this approach for a project.

  • Build times are longer: Compiling to C and then running a C compiler takes longer than building a typical PyInstaller bundle. The difference becomes more noticeable as your application grows, which can matter if you’re compiling frequently in a CI pipeline.
  • You need a working C compiler: This is an extra dependency that PyInstaller doesn’t require. On Windows, Nuitka’s downloadable MinGW64 toolchain doesn’t normally support Python 3.13 or newer, so you’ll need another supported compiler option. The Windows builds in this tutorial used MSVC 14.5.
  • Some compiler combinations may need a workaround: Nuitka supports multiple compiler backends, and Zig was tested as an alternative during this tutorial’s Windows testing. With CPython 3.13.15, Nuitka 4.2.1, and Zig 0.16.0, the standalone build compiled successfully but failed at startup with ImportError: Frozen object named 'encodings' is invalid. Rebuilding the same application with MSVC succeeded. This doesn’t establish the underlying cause, but trying another supported compiler may be a practical troubleshooting step if you encounter a similar failure.
  • Some packages need extra configuration: Libraries that rely on dynamic imports, plugins, or non-standard packaging can require additional options to make sure everything your application needs ends up in the distribution.
  • Debugging compiled applications is less convenient: Once your code is compiled, working with the resulting application can be less straightforward than debugging an ordinary Python script.
  • Builds are platform-specific: A Windows build targets Windows, while Linux and macOS builds target their respective platforms. You generally need to build separately for the operating systems you intend to support.
  • Standalone and onefile builds come with different trade-offs: A standalone build means shipping a folder instead of a single file. In this tutorial’s Windows word-count test, the onefile build’s median total runtime was about seven times that of the standalone build, using the default onefile settings. Because the workload is short, the comparison mainly reflects onefile’s startup overhead.
  • Support for the newest Python version can lag behind official releases: Nuitka may need time to add full support for a newly released Python version. If you’re using a just-released version, then check Nuitka’s documentation and release notes before choosing it for a project.

Finally, keep in mind that the performance numbers you saw are specific to a CPU-bound benchmark on one machine. The speedup depends heavily on your workload and environment, so measure it on your own code rather than assuming the same gains.

Conclusion

Nuitka gives you a different way to distribute Python applications: instead of bundling your code with an interpreter, it compiles your code to C first.

In this tutorial, you’ve learned how to:

  • Install Nuitka and build your first standalone executable
  • Choose between the --mode=standalone, --mode=onefile, and --mode=app builds
  • Measure distribution size and startup time, and test runtime speed on a CPU-bound benchmark
  • Decide when Nuitka is a better fit than PyInstaller

If your own benchmarks show a meaningful performance improvement and you’re willing to take on a C compiler dependency and longer build times, Nuitka is worth considering. If you mainly need a reliable way to distribute a Python application without requiring Python on the target machine, and you don’t need the performance benefits of compilation, PyInstaller’s simpler setup is still a solid default.

From here, you might explore packaging GUI applications with Nuitka, its more advanced options, or platform-specific builds as part of a CI pipeline. The official documentation is a good next stop. If you want to compare the two approaches directly, Real Python’s guide on Using PyInstaller to Easily Distribute Python Applications is a good place to start.

Frequently Asked Questions

Now that you have some experience with Nuitka in Python, you can use the questions and answers below to check your understanding and recap what you’ve learned.

These FAQs are related to the most important concepts you’ve covered in this tutorial. Click the Show/Hide toggle beside each question to reveal the answer.

Nuitka compiles your Python code to C and then builds a native executable from it. PyInstaller doesn’t compile your code. Instead, it bundles your code with the Python interpreter and its dependencies.

It can, depending on the workload. In this tutorial’s benchmark, the compiled CPU-bound code ran about 1.5 times as fast as regular Python, but code that mostly waits on I/O or calls optimized C extensions sees much smaller gains. Measure your own code before assuming a speedup.

The --mode=standalone option creates a folder that holds the executable and the files it needs, so it starts quickly. The --mode=onefile option packs everything into a single file, which is easier to distribute but starts more slowly because it unpacks its contents before the application runs.

Yes. Nuitka translates your code to C, so it needs a supported C compiler to build the executable. On Windows with Python 3.13 or newer, Nuitka’s downloadable MinGW64 toolchain doesn’t normally work, so MSVC is the usual choice.

Nuitka makes casual inspection harder because it compiles your modules instead of shipping them in their usual Python form. It isn’t strong code protection, though, and determined reverse engineering is still possible.

Take the Quiz: Test your knowledge with our interactive “Nuitka: Compile Python Into a Standalone Executable” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

Nuitka: Compile Python Into a Standalone Executable

Test your understanding of compiling Python with Nuitka, from standalone and onefile builds to speedups and when PyInstaller fits better.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Dictionary merging in Python 3.5+

About Shanzia Shabnom Mithun

Shanzia is a Machine Learning Engineer and Python enthusiast with a background in machine learning, data science, and research. She enjoys using Python to explore new technologies and build practical solutions to real-world problems.

» More about Shanzia Shabnom

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Master Real-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

Master Real-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal.


Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!