Py2Native Python to native compilerPython-zu-Native-Compiler

← All posts

2026-11-01

Automate Compiling Python to Native Binaries in CI/CD

Automate Compiling Python to Native Binaries in CI/CD
python compiler cython code protection open source

Automate Compiling Python to Native Binaries in CI/CD

Somewhere in your release process there is a terminal window that only one person knows how to open. It runs the native build, copies the wheel out of dist/, drops the embedded runtime somewhere on a share, and zips it up. If that person is on holiday, the release waits.

Native builds are exactly the kind of task that should never be manual. They are deterministic, they are repetitive, and they fail in boring ways — a missing MSVC toolchain, a Python version drift, a forgotten --wheel flag. Every one of those failures costs you a release cycle when it happens on a laptop at 6pm, and costs you nothing when it happens on a CI runner at 6pm.

This article walks through automating Py2Native builds end to end: the one-time setup, real GitHub Actions and GitLab CI configurations, license verification inside the pipeline, and the failure modes you should wire alerts for.

Why Manual Native Builds Don’t Scale

The manual loop looks harmless on paper: run the compiler, collect the artifact, upload it. In practice, each step accumulates drift.

The compiler flags are the sneakiest part. A build on a developer’s machine silently picks up whatever MSVC, GCC, or Clang version is installed. Two engineers on the same team can produce binaries linked against different CPython shared libraries and never notice until a customer reports an import error on a specific distro.

Forgotten optional steps are the second problem. A library build without --wheel gives you a .pyd/.so that nobody can install cleanly. A build without --embed gives you a deployment directory that has to be assembled by hand. These flags are not hard to type — they’re hard to remember consistently across people, branches, and release candidates.

And then there is the “works on my machine” artifact. If the binary was produced from an uncommitted working tree, the shipped artifact does not correspond to any commit in your history. That is a compliance problem, not just a convenience problem.

Automation fixes all three by making the build a function of the commit: every push triggers the same command, on the same pinned Python, with the same flags, and produces an artifact you can trace back to a SHA.

It also removes the temptation to do it the hard way. Protecting Python with raw Cython means hand-writing a bootstrap.pyx, calling cythonize yourself, wiring up setup.py extensions for the C step, and then repeating that for every platform. Py2Native hides that entire pipeline behind one build command — you write plain Python, and the tool handles Cython transpilation, C compilation, and linking. That is what makes it a realistic candidate for CI in the first place.

One-Time Setup: Prepare Your Project and CI Runner

Before any workflow file exists, get the build working locally in the same shape CI will use it.

Install uv and Py2Native

Py2Native is driven through uv, so uv is the only thing your runner needs to bootstrap:

# install uv (Linux/macOS)
curl -LsSf https://astral.sh/uv/install.sh | sh

# add the open-source compiler to your project
uv add py2native

The core compiler requires cython >= 3.2.4, setuptools >= 82.0.1, and uv >= 0.11.8; uv add resolves these for you. On Linux, auditwheel >= 6.6.0 is used to repair wheels for manylinux compliance.

Make sure a C toolchain exists on the runner

Py2Native does not bundle a compiler — it drives the platform one:

  • Windows: MSVC (the windows-latest GitHub runner has it; on other agents install Visual Studio Build Tools)
  • Linux: GCC (build-essential)
  • macOS: Clang (Xcode Command Line Tools)

Supported targets are Windows 8+, manylinux2014/musl Linux, and macOS, on x86-64 or ARM64, with CPython 3.11–3.15 (including the free-threaded 3.14t and 3.15t builds).

Pin the entry point and the source set

Keep a single obvious entry module — main.py at the project root is the convention — and keep your proprietary modules under a directory you can address with a glob, for example src/. Py2Native expands glob patterns itself, which matters later: shells like cmd.exe and PowerShell do not expand *.py, so quoting the pattern and letting the tool resolve it is the portable option.

uv run py2native build main.py "*.py" --base src --wheel dist --embed deploy

That one command produces both artifacts: a PEP 427 wheel containing your compiled modules, and a uv-managed deployment directory.

Optional: add the Pro plugin for license enforcement

If you sell per-customer licenses, add the closed-source plugin now rather than retrofitting it later:

uv add py2nativepro
uv run py2native keygen private.pem public.pem

keygen generates an EC P-256 keypair. Keep private.pem out of the repository and out of CI logs — it belongs in your CI secret store, or better, on the machine that issues licenses. Only public.pem ever needs to reach the build. Wiring the verification into the pipeline is covered below.

Building the Automated Pipeline: CI Workflow Examples

GitHub Actions

A matrix job across the three desktop platforms, triggered on every push to main, every tag, and every pull request:

name: native-build

on:
  push:
    branches: [main]
    tags: ["v*"]
  pull_request:

jobs:
  build:
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-latest
            artifact: linux-x86_64
          - os: windows-latest
            artifact: windows-x86_64
          - os: macos-14
            artifact: macos-arm64
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v4

      - name: Install uv
        uses: astral-sh/setup-uv@v3

      - name: Install dependencies
        run: uv sync --frozen

      - name: Compile to native
        run: uv run py2native build main.py "*.py" --base src --wheel dist --embed deploy

      - name: Smoke test the artifact
        run: uv run python smoketest.py

      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: native-${{ matrix.artifact }}
          path: |
            dist/
            deploy/

--frozen makes uv sync fail instead of silently resolving newer versions — the reproducibility guard from the previous section, enforced by the runner.

GitLab CI

The same command, with the uv cache carried between jobs:

stages:
  - build

native-linux:
  stage: build
  image: python:3.13-bookworm
  variables:
    UV_CACHE_DIR: .uv-cache
  cache:
    key: uv-$CI_COMMIT_REF_SLUG
    paths:
      - .uv-cache
  before_script:
    - apt-get update && apt-get install -y build-essential
    - curl -LsSf https://astral.sh/uv/install.sh | sh
    - export PATH="$HOME/.local/bin:$PATH"
    - uv sync --frozen
  script:
    - uv run py2native build main.py "*.py" --base src --wheel dist --embed deploy
    - uv run python smoketest.py
  artifacts:
    paths:
      - dist/
      - deploy/
    expire_in: 1 week

Other CI systems

Jenkins, CircleCI, Buildkite, and friends do not need a plugin — they need a shell script and a trigger. Put the build in a checked-in script so the pipeline definition stays thin:

#!/usr/bin/env bash
# ci/build-native.sh
set -euo pipefail
uv sync --frozen
uv run py2native build main.py "*.py" --base src --wheel dist --embed deploy
uv run python smoketest.py

Then trigger it from whatever calls your pipeline, for example a Jenkins job triggered over HTTP after a merge:

curl -X POST "$JENKINS_URL/job/native-build/buildWithParameters" \
  --user "$JENKINS_USER:$JENKINS_TOKEN" \
  --data-urlencode "GIT_SHA=$GITHUB_SHA"

The important part is that the script is identical everywhere. A webhook trigger is only as reproducible as the command it runs.

Including license verification in the build

With the Pro plugin installed, add --license and --public to the build command. The plugin performs the license check during build dispatch and refuses to produce an artifact without a valid license:

uv run py2native build main.py "*.py" --base src --wheel dist --embed deploy \
  --license license.dat \
  --public public.pem

That flag-level check is the build-time half. The runtime half is the part that keeps working after a customer renames an environment variable: the public key and the compiled ES256 verification code are baked into the executable, and your code calls it through a declared signature.

The Pro plugin ships a .pxd stub so the signature is available at compile time:

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

In the module where you gate startup, cimport it and pass the license string:

from _p2n_bootstrap cimport _runtime_verify_es256_jwt

license = _runtime_verify_es256_jwt(
    licenseString,
    expected_iss="RSJ Software GmbH",
    expected_aud="TimestampGIT",
)

This is the one place the build touches anything Cython-shaped, and it is deliberate: the verification logic is compiled into your binary alongside the public key, so there is no third-party crypto library to ship and no Python source describing the check. The rest of your codebase stays plain Python. For a deeper walkthrough of the runtime side, see Verify a License Key Inside a Compiled Python Binary.

Generate license.dat with the private key on your licensing machine, then verify it before shipping:

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

In CI, pass license.dat and public.pem from your secret store — never commit private.pem.

Monitoring Builds and Handling Failures

A pipeline nobody watches is just a slower manual process. Three things are worth wiring up:

Capture the artifacts and the logs together. Upload dist/ and deploy/ as CI artifacts on every build, not just on tags. When a customer reports a crash, you want the exact binary from the exact commit, plus the compiler output that produced it. Both GitHub Actions and GitLab CI keep artifacts for a configurable retention window.

Notify on failure, not on success. Success notifications train people to ignore them. Route failures to Slack, Teams, or email through your CI’s native integration — a red build on main should be noisy within minutes.

Know the three failure modes you will actually hit:

  • Missing or mismatched toolchain. “Unable to find vcvarsall” on Windows and “cannot find -lpython” on Linux both mean the compiler or the CPython shared library is not where the linker expects. Pin your runner image.
  • Python version out of range. Anything outside 3.11–3.15 fails early and loudly. Pin the interpreter in the workflow rather than inheriting the runner default.
  • License verification failure. An expired JWT, a --license file that was never uploaded, or a mismatched --public key aborts the build. uv run py2native show --public public.pem license.dat prints the claims so you can see the expiry before you re-run.

Run the smoke test against the compiled artifact, not the source tree. smoketest.py should import from the wheel or the embedded directory and assert that the entry point starts. That catches library-mode packaging mistakes — a wheel missing its __init__.py meta-path finder will import-fail for the user but “build fine” in CI.

Best Practices for Reliable Native Builds

  • Pin everything. Commit uv.lock, run uv sync --frozen in CI, and pin the Python version in the workflow. Native builds amplify version drift because the artifact is opaque.
  • Cache the uv package cache. astral-sh/setup-uv and UV_CACHE_DIR both work; caching cuts minutes off every matrix leg.
  • Use a matrix, not a monolith. Windows, Linux, and macOS runners, crossed with the Python versions you support. fail-fast: false keeps one platform failure from hiding the others.
  • Compile only your code. Third-party libraries stay as Python source and work as-is — Py2Native compiles your custom modules, so you never write build configuration for dependencies. This also keeps LGPL libraries replaceable by the end user, which is what compliance reviewers want to hear. For the on-premise licensing angle, see Python Licensing for On-Premise Deployments.
  • Keep module names unique. Py2Native cannot handle modules with identical names across source files — a good reason to namespace internal modules rather than rely on implicit package boundaries.
  • Skip the hard way. Hand-written .pyx/.pxd files, manual cythonize calls, and bespoke C extensions as a protection strategy all need per-platform CI configuration you now own forever. Write plain Python, run one command, let the tool handle the toolchain.
  • Remember what compilation does and does not do. It protects your source. It does not prevent monkey-patching, and it does not change the fact that __init__.py is skipped as a namespace marker.

FAQ

Can I automate builds for multiple platforms in one CI pipeline?

Yes. Use a build matrix in your CI configuration to run uv run py2native build on Windows, Linux, and macOS runners. Py2Native handles platform-specific compilation and linking automatically — the same build command produces a .pyd on Windows and a .so on Linux without workflow changes.

How do I handle license verification in CI with the Pro plugin?

Install the Pro plugin (uv add py2nativepro), generate a keypair with uv run py2native keygen, and sign a license with uv run py2native sign. Then pass --license and --public to the build command. The plugin bakes the public key and verification logic into the binary, and your .pxd-declared _runtime_verify_es256_jwt call performs the runtime check.

What if my project uses third-party libraries?

Third-party libraries remain as Python source and work as-is. Py2Native only compiles your custom modules, so you don’t need to configure builds for dependencies — no per-package build settings, no vendored source trees.

Do I need to write Cython code to use Py2Native?

No. You write plain Python. Py2Native handles Cython transpilation, C compilation, and linking behind the scenes — no .pyx files, no .pxd declarations except the optional Pro license signature, and no manual cythonize step.

Ship on Every Commit

The manual build ritual persists because it feels safe: a human looks at the output before it ships. But a human looking at a .so file learns nothing, while a CI pipeline that reproduces the artifact from a commit SHA tells you everything — what went in, what compiler built it, and whether the smoke test passed.

Set it up once. uv add py2native, a workflow file with three matrix legs, and one uv run py2native build main.py "*.py" --wheel dist --embed deploy line. After that, every merge produces a protected native binary without anyone opening a terminal.

Ready to stop building by hand? Start with Py2Native and put the compiler in your pipeline this week. If you are still deciding what needs protecting in the first place, read How to Protect Python Source Code Before You Ship It first.

Related posts

EU label: AI-generated content