Py2Native Python to native compilerPython-zu-Native-Compiler

← All posts

2026-11-09

Compile Plain Python to Native Code Without Rewriting in C

Compile Plain Python to Native Code Without Rewriting in C
python compiler cython code protection open source

Compile Plain Python to Native Code Without Rewriting in C

You have a Python application you want to ship as a protected binary. The usual advice goes something like: “write a C extension,” “rewrite the hot parts in Cython,” “add .pyx files and a build script.” That advice is technically correct and practically awful — it means maintaining two codebases and re-learning your own project.

This article walks through the other path: taking plain Python — the code you already have — and compiling it to native machine code with no C rewrite, no Cython syntax scattered through your files, and no manual cythonize step. You’ll set up the toolchain, build an executable and a wheel, optionally bolt on signed license verification, and then prove the source really is gone. The hard way (hand-written C extensions, .pxd files everywhere, distutils glue) is mentioned here only so you can recognize it when someone recommends it. Py2Native is the shorter route.

Why You Don’t Need to Rewrite Python in C

The misconception is baked into the tooling. Historically, “protecting Python” meant “leaving Python”: you converted modules to C extensions by hand, or you learned Cython’s cdef/cpdef dialect and wrote .pyx files alongside your .py files, then wired a setup.py that called cythonize() before build_ext. Every refactor touched two languages.

Py2Native collapses that. You point it at your sources; it generates the bootstrap module, runs Cython to transpile each .py to C, compiles the C with your platform compiler, and links the result into a native binary. Cython is still under the hood — it’s just not your problem anymore. There is no .pyx file to author, no cythonize invocation to remember.

Two consequences matter for shipping:

  • Third-party libraries are left unmodified. Py2Native compiles your code. NumPy, Requests, and friends stay as ordinary installed packages and keep working with minimal or no configuration. You’re not asked to write build recipes for your dependency tree.
  • The output is a real binary. An executable, a shared library, or a PEP 427 wheel wrapping a compiled shared object — not a self-extracting archive with your source sitting inside it.

The rest of this is the walkthrough.

Prerequisites for Compiling Python to Native Code

Confirm the following before you start:

  • CPython 3.11–3.15, including the free-threaded builds 3.14t and 3.15t.
  • A platform C compiler/linker: MSVC on Windows, GCC on Linux, Clang on macOS.
  • A supported OS: Windows 8+, manylinux2014 or musl Linux, macOS.
  • x86-64 or ARM64 CPU.
  • Internet access during the build — Py2Native downloads Python distributions and libraries.

Add the compiler to your environment. On Linux, sudo apt install build-essential. On macOS, xcode-select --install. On Windows, install the Visual Studio Build Tools with the C++ workload.

Then install the compiler package with uv:

uv add py2native

The open-source core (py2native, MIT licensed) pulls in cython >= 3.2.4, setuptools >= 82.0.1, uv >= 0.11.8, and auditwheel >= 6.6.0 on Linux for manylinux repair. If you want JWT license verification or string compression, add the commercial Pro plugin:

uv add py2nativepro

The Pro plugin loads dynamically at build time — the core compiler doesn’t need to know about it.

Step-by-Step: Compile Your Python Project to a Native Binary

Step 1 — Lay out the project

A conventional layout works as-is. No build file, no manifest:

myapp/
├── main.py
├── licensing.py
├── licensing.pxd        # only needed for the Pro license step
├── payload.json
└── mypackage/
    ├── __init__.py
    ├── core.py
    └── reporting.py

One constraint to check now: no two source files may share a module name. mypackage/core.py and legacy/core.py will collide — rename one.

Step 2 — Run the build

main.py is the main module; everything after it is a source pattern (globs allowed, expanded relative to --base):

uv run py2native build main.py "*.py" "mypackage/*.py" --base .

Under the hood, build.py globs the sources, compiler.py generates bootstrap.pyx from its templates and invokes Cython, getCompiler() compiles the resulting C with platform flags from winplatform.py / linuxplatform.py / macplatform.py, and the linker produces the final artifact.

Step 3 — Pick your output mode

The default is a standalone native executable. Other modes are flags on the same command:

# Shared library instead of an executable
uv run py2native build main.py "mypackage/*.py" --library --wheel dist/

# uv-managed deployment directory (manifest + bundled distribution)
uv run py2native build main.py "mypackage/*.py" --embed deploy/

# Windows GUI app: no console window
uv run py2native build main.py "mypackage/*.py" --no-console
Flag Output
(none) Native executable
--library .pyd / .so / .dylib
--wheel <dir> PEP 427 wheel containing the compiled shared library
--embed <dir> uv-managed deployment directory

Step 4 — Understand what library mode ships

--library produces one compiled shared object holding all your modules, and the wheel builder adds two generated files:

  • __init__.py — a meta-path finder that redirects import mypackage.submodule into the native library.
  • __main__.py — makes python -m mypackage work.

Both are required. Without the finder, Python’s import system can’t see your compiled modules; without the entry point, there’s nothing to run. Don’t hand-edit them — regenerate on each build.

Step 5 — (Optional) Add license verification with the Pro plugin

If you sell your software, you want the binary to refuse to run without a valid key. Generate an EC P-256 keypair:

uv run py2native keygen private.pem public.pem

Write your claims to payload.json, then sign them into a JWT:

uv run py2native sign --private private.pem payload.json license.dat
uv run py2native show --public public.pem license.dat

show prints the claims and, with --public, verifies the signature.

Now wire the check into your code. The Pro plugin compiles the ES256 verification routine into your binary, so your module calls it through a declaration file rather than a Python import. Drop the .pxd next to the module that calls the verifier:

# licensing.pxd
cdef _runtime_verify_es256_jwt(token, expected_iss=*, expected_aud=*)

And call it from that module:

# licensing.py
from _p2n_bootstrap cimport _runtime_verify_es256_jwt

def check_license(licenseString: str) -> bool:
    license = _runtime_verify_es256_jwt(licenseString, expected_iss="RSJ Software GmbH", expected_aud="TimestampGIT")
    return bool(license)

Use it at startup in main.py:

import sys
import pathlib
from licensing import check_license
from mypackage.core import run

token = pathlib.Path("license.dat").read_text().strip()
if not check_license(token):
    sys.exit("Invalid or missing license.")

run()

Two design notes worth knowing before you ship:

  • Only the public key is stored in the executable. The private key never leaves your build machine.
  • The elliptic-curve verification is compiled into the binary by the plugin itself — no third-party crypto library is loaded at runtime, so there’s nothing to swap out or monkey-patch in the verification path.

Step 6 — Build with the license wired in

uv run py2native build main.py "*.py" --license license.dat --public public.pem

The Pro plugin runs during extendBuild(), embeds public.pem, and links the compiled verification code into the executable. Verify the packaging decisions with uv run py2native show --public public.pem license.dat before you hand the binary to anyone.

How to Confirm Your Python Code Is Now Native

Don’t take the build log’s word for it. Three checks:

1. Inspect the artifact type.

file ./dist/main
# ./dist/main: ELF 64-bit LSB pie executable, x86-64, dynamically linked ...

On Windows you’ll see PE32+ executable, on macOS Mach-O 64-bit executable. For a wheel, unzip -l dist/*.whl should show a compiled .pyd/.so plus the generated __init__.py and __main__.py — and no .py copies of your business logic.

2. Run it with the sources gone. Move your .py files out of the tree and execute the binary:

mkdir /tmp/parked && mv main.py licensing.py mypackage/*.py /tmp/parked/
./dist/main
mv /tmp/parked/* .

If it still runs, the logic is genuinely inside the binary.

3. Exercise the license path. Run once with a valid license.dat, once with a garbage token, and once with no token at all. You want a clean failure each time — an app that starts anyway means your check isn’t on the startup path.

Troubleshooting Common Compilation Issues

“No C compiler found” / link errors. Almost always a toolchain problem, not a Py2Native one. Install MSVC Build Tools on Windows, GCC on Linux, or the Xcode command-line tools on macOS, then confirm cl / gcc / clang is on PATH. On Linux, missing auditwheel breaks the manylinux repair step — it’s installed as a dependency, so a failure here usually means the wheel step ran in a different environment than the build.

ImportError or wrong module loaded after compilation. You have two source files with the same module name. The compiler requires unique module names across the whole source set; rename and rebuild.

__init__.py seems to be missing from the output. It’s intentional — __init__.py is skipped during compilation because it’s a namespace marker, not compilable code. In library mode the wheel builder writes its own __init__.py and __main__.py, and __main__.py is excluded from your source list for the same reason.

Someone can still monkey-patch a third-party library. Correct, and expected. Third-party packages stay as Python source, so patching them remains possible. If your compliance posture requires it, LGPL libraries also remain replaceable by the end user. Py2Native protects your code, not the dependency graph.

FAQ

Do I need to rewrite my Python code in C or Cython to use Py2Native? No. Py2Native compiles plain Python directly to native machine code. You write normal Python — no .pyx files, no manual cythonize step — and Py2Native handles the Cython transpilation and C compilation under the hood. The one place a declaration file appears is the optional Pro license check.

Will my third-party Python libraries still work after compilation? Yes. Third-party libraries are left unmodified and work as-is with minimal or no configuration. Py2Native only compiles your custom code, so dependencies like NumPy or Requests continue to function normally.

How do I add license key verification to my compiled Python app? Use the Pro plugin (py2nativepro). Generate an EC P-256 keypair with uv run py2native keygen, sign a JWT payload with uv run py2native sign, and include the provided .pxd file to call _runtime_verify_es256_jwt in your code. Build with --license and --public to embed the public key and verification logic into the executable.

Is compiled Python really unreadable? Compiled Python is significantly harder to reverse-engineer than source code, but no protection is absolute. For an honest assessment, see our article Is Compiled Python Really Unreadable? An Honest Look.

Conclusion

The rewrite-in-C advice exists because, for a long time, there was no alternative that produced a genuine native artifact from unmodified Python. There is now: install with uv, point uv run py2native build at your sources, choose an executable, a library, a wheel, or an embedded deployment directory, and ship. Your Python stays Python; the deliverable doesn’t.

Start with the open-source core and a single build — uv run py2native build main.py "*.py" — and confirm with file that you’ve got a native binary. When you’re ready to gate distribution behind signed keys, add the Pro plugin and the startup check above.

Related posts:

EU label: AI-generated content