I have a Mac app whose backend is about 24,000 lines of plain-stdlib Python. When I wrote the Windows and Linux version in Rust, I didn't want to rewrite that backend or maintain two copies, and I didn't want users to install anything besides the app. This is how I ended up shipping the Python backend inside a single Rust executable, and what went wrong on Windows.
The app is JoeBro Desktop, a local-first workspace for AI agents (GPL-3.0, I made it). The relevant part here is only the packaging.
The shape of it
The Rust app is the UI. The backend is a Python process listening on 127.0.0.1. The UI starts it on launch and stops it on quit. There is nothing to pip install, because the backend only uses the standard library.
The trick that keeps this to one file is a zipapp. Python can run a zip file that has a __main__.py in it (python thing.pyz). So:
- A build script zips the backend's
.pyfiles plus a small shim__main__.pyintojoebro_backend.pyz(about 700 KB). - Rust embeds that archive with
include_bytes!. - At startup, Rust writes the bytes to the data directory and runs
python joebro_backend.pyz.
static PYZ: &[u8] = include_bytes!("../backend/joebro_backend.pyz");
You can't run Python from memory, so the file has to land on disk. I name it by a hash of the contents so an app update writes a new file and deletes the old ones:
let mut h: u64 = 0xcbf29ce484222325; // FNV-1a over the archive
for b in PYZ {
h = (h ^ *b as u64).wrapping_mul(0x100000001b3);
}
let p = dir.join(format!("joebro_backend-{h:016x}.pyz"));
FNV-1a is not a security measure here, just a cheap "is this the same archive" check. The build script uses fixed timestamps for every zip entry, so the archive is byte-identical for the same sources and the hash only changes when the code does.
The honest limitation
This does not embed Python. The machine needs Python 3.10 or newer. On Linux that is nearly always already there. On Windows it usually isn't, so the app shows a message with winget install Python.Python.3.12 and a Check again button, and it offers a "connect to a server" mode that needs no Python at all.
I chose that over bundling an interpreter because it keeps the download small and keeps the backend identical to the Mac one. If you're building something similar for non-technical users, think hard about whether that trade is right for you.
Finding Python turned out to be fiddly enough to deserve its own function:
- Try a configured override, then
python3, thenpython, then on Windowspy -3. - Run each candidate with
-c "import sys; print(...)"and parse the version, instead of trusting the name. - On Windows, skip anything under
WindowsApps. Those are the Microsoft Store "app execution alias" stubs: running one opens the Store instead of Python. - Distinguish "no Python" from "Python 3.8", so the error message can say which.
Process management details
None of these are clever, but each one cost me an evening.
The token goes in the environment, not on the command line. The backend demands a random bearer token on every request. The app generates 32 random bytes on first start, saves them in a file with mode 0600, and passes them to the child as JOEBRO_TOKEN. Command lines are visible to other users in a process list on many systems; environment variables are much harder to read.
Port selection. Prefer 8765, and if something is already there, bind port 0 and let the OS choose. The app then polls /api/health for up to 25 seconds before calling the backend started, and it keeps the tail of the log to show in the error if it doesn't.
Orphans. If the Rust app crashes, you don't want a Python server left behind. The shim takes --parent-pid and a daemon thread checks every two seconds that the parent still exists, then calls os._exit(0). Checking whether a PID is alive is different on each platform. On Unix, os.kill(pid, 0) works. On Windows you open the process and compare the exit code to 259 (STILL_ACTIVE):
h = k.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
...
return code.value == 259 # STILL_ACTIVE
Clean shutdown. On quit the app calls POST /api/shutdown so SQLite closes properly, waits up to three seconds, and only then kills the process. The shim adds that endpoint by wrapping the backend's request handler, so the shared backend code doesn't need to know about desktop hosting.
No console window flash. On Windows a GUI app that spawns Python gets a console window unless you pass CREATE_NO_WINDOW (0x08000000) in the creation flags.
The Windows shims
The backend was written on macOS and uses fcntl.flock and os.fchmod. Neither exists on Windows Python. Rather than edit the shared backend, the shim installs stand-ins before importing it:
m = types.ModuleType("fcntl")
m.LOCK_EX, m.LOCK_SH, m.LOCK_UN, m.LOCK_NB = 2, 1, 8, 4
m.flock = lambda *a, **k: None
sys.modules["fcntl"] = m
This is a no-op lock. It's fine here because only one process (this app's own backend) writes to that data directory, but it's worth saying out loud: it's a shim, not a port.
The time zone database gotcha
This is the one that actually got through to CI.
I have an end-to-end test that starts the real bundled backend, points it at fake servers, and calls its API. On Linux it passed. On the Windows runner it failed with:
events failed: HTTP 502: CalDAV sync failed: 'No time zone found with key UTC'
Python's zoneinfo reads the IANA time zone database from the operating system. Linux and macOS have one in /usr/share/zoneinfo. Windows does not, and the Windows builds of Python don't bundle one either. The PyPI package tzdata exists for exactly this case: zoneinfo falls back to it when it is importable. A backend that calls ZoneInfo("UTC") works everywhere except a stock Windows install.
Since the whole point was "nothing to install", I vendored the tzdata wheel (about 350 KB) into the repo and had the build script copy its tzdata/ package into the zipapp:
for whl in sorted((here / "vendor").glob("tzdata-*.whl")):
with zipfile.ZipFile(whl) as w:
for n in sorted(w.namelist()):
if n.startswith("tzdata/") and not n.endswith("/"):
z.writestr(...)
A wheel is a zip file, so this is just copying entries from one zip into another. Python's import system reads from the .pyz, so import tzdata works and zoneinfo finds the data. The lesson I took from it: the tests I ran on my own Linux machine said nothing about what a clean Windows machine has. Running the real end-to-end test on a Windows runner caught it before a user did.
What I'd do again, and what I'd change
I'd do again: one shared backend, a shim for host-specific behaviour, a hash-named file in the data directory, and testing the actual packaged thing on every OS in CI.
What I'd reconsider: needing a system Python at all. If your users are developers, as mine mostly are, it's reasonable. If they aren't, an embedded interpreter or a rewrite of the hot path in Rust might be worth the size.
The code is open if you want to read it: the process management is src/backend.rs, the packaging is backend/build_pyz.py, and the shim is backend/shim/__main__.py in JoeBro-Desktop. If you've solved "ship a Python backend with a native app" differently, I'd like to hear how.
Top comments (0)