Concept Explanation
You have built a working application. Now you want to give it to someone who has never heard of Python, has no interpreter installed, and will not open a terminal. "Just run pip install -r requirements.txt first" is not an answer for them.
Packaging turns your .py files into a single executable — MyApp.exe on Windows, MyApp.app on macOS, a binary on Linux — that bundles the interpreter, your code, and every dependency into one artifact the user can double-click.
How It Actually Works
This is not compilation. There is no machine code translation. A packager:
- Traces your imports to find every module you use.
- Copies those modules, plus the CPython interpreter itself, into a folder.
- Wraps it in a small launcher — a bootloader — that unpacks to a temp directory and runs your entry point.
The consequences follow directly from that: the output is large (30–80 MB is normal), start-up is slower than python app.py, and the binary only runs on the platform that built it. There is no cross-compiling. A Windows .exe must be built on Windows.
The Tools
| Tool | Strength | Trade-off |
|---|---|---|
| PyInstaller | Widest support, best docs, handles GUI toolkits well | Large output |
| Nuitka | Genuinely compiles to C; faster and harder to decompile | Slower builds, needs a C compiler |
| cx_Freeze | Cross-platform, clean config | Fewer recipes for tricky libraries |
| briefcase | Produces proper native installers (MSI, DMG) | More setup, opinionated project layout |
Start with PyInstaller. Reach for the others when it does not suffice.
The Flags That Matter
pip install pyinstaller
pyinstaller --onefile --windowed --name "Notes" --icon app.ico main.py
| Flag | Effect |
|---|---|
--onefile | One executable instead of a folder of files |
--windowed | No console window behind your GUI (--noconsole is an alias) |
--name | The output name |
--icon | Application icon (.ico on Windows, .icns on macOS) |
--add-data | Bundle non-Python files: images, fonts, JSON |
--hidden-import | Force-include a module PyInstaller could not detect |
--clean | Wipe caches — the first thing to try when a rebuild misbehaves |
The Hard Part: Data Files
--onefile unpacks to a random temporary folder at run time, so open("logo.png") — which resolves relative to the current working directory — fails on the user's machine while working perfectly in development. Every packaged app needs this helper:
import sys
from pathlib import Path
def resource_path(relative):
"""Return the correct path whether running from source or frozen."""
base = getattr(sys, "_MEIPASS", None) # PyInstaller sets this only when frozen
root = Path(base) if base else Path(__file__).parent
return root / relative
Code Example #1 (Basic)
A minimal app packaged with its icon.
# main.py
import tkinter as tk
from tkinter import ttk
import sys
from pathlib import Path
def resource_path(relative):
base = getattr(sys, "_MEIPASS", None)
root = Path(base) if base else Path(__file__).parent
return root / relative
root = tk.Tk()
root.title("Packaged App")
root.geometry("300x140")
# Works both from source and from the frozen binary
notice = resource_path("VERSION.txt")
version = notice.read_text().strip() if notice.exists() else "dev"
ttk.Label(root, text=f"Hello from a real executable!").pack(pady=(24, 4))
ttk.Label(root, text=f"version {version}").pack()
ttk.Button(root, text="Close", command=root.destroy).pack(pady=12)
root.mainloop()
Build it:
pyinstaller --onefile --windowed --name "HelloApp" \
--add-data "VERSION.txt:." main.py
# Result: dist/HelloApp.exe (or dist/HelloApp on macOS/Linux)
The --add-data separator is : on macOS and Linux but ; on Windows. That inconsistency causes a lot of confused bug reports.
Code Example #2 (Intermediate)
A .spec file — the reproducible way to build once you have more than three flags.
# HelloApp.spec -- generated by PyInstaller, then edited by you
# Build with: pyinstaller HelloApp.spec
block_cipher = None
a = Analysis(
["main.py"],
pathex=[],
binaries=[],
datas=[
("assets/logo.png", "assets"), # (source, destination-inside-bundle)
("assets/theme.json", "assets"),
("VERSION.txt", "."),
],
hiddenimports=[
"PIL._tkinter_finder", # a classic PyInstaller cannot find alone
],
excludes=[
"matplotlib", # not used -- saves ~40 MB
"numpy.tests",
"tkinter.test",
],
cipher=block_cipher,
)
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
exe = EXE(
pyz,
a.scripts,
a.binaries,
a.datas,
name="HelloApp",
console=False, # same as --windowed
upx=True, # compress, if UPX is installed
icon="assets/app.ico",
)
Commit the .spec file. It is the difference between "run this one command" and a paragraph of flags someone will get wrong.
Common Mistakes
- Expecting to cross-compile: you cannot build a Windows
.exeon a Mac. Use a CI matrix (GitHub Actions withwindows-latest,macos-latest,ubuntu-latest) to build all three from one push. - Relative paths to data files: works in development, breaks in
--onefile. Use theresource_pathhelper above, always. - Building from your global Python: PyInstaller bundles everything importable, so a global environment with 200 packages produces a 400 MB binary. Build from a clean virtual environment containing only your real dependencies.
- Forgetting
--windowedon a GUI app: your users get an ugly black console window behind the window they wanted. - Assuming a hidden import will be found: dynamic imports (
importlib.import_module(name)), plugin systems, and some libraries' internals are invisible to static analysis. The symptom isModuleNotFoundErroronly in the built version. Fix with--hidden-import. - Never testing on a clean machine: your own computer has Python, Visual C++ runtimes, and half the world's DLLs already installed. Test in a fresh VM or container.
- Being surprised by antivirus warnings: unsigned single-file executables that unpack to temp look exactly like malware to heuristic scanners. This is expected, and the only real fix is code signing.
Best Practices
- Build in a clean virtualenv: create it, install only what you import, then package. This is the single biggest lever on output size.
- Use a
.specfile for anything real: reproducible, reviewable, diffable. - Automate builds in CI: one workflow producing all three platform artifacts on every tag removes the "works on my machine" class of bug entirely.
- Prefer
--onedirwhile debugging: you can inspect what actually got bundled; switch to--onefilefor release. - Exclude what you do not use:
excludes=["matplotlib", "numpy.tests"]regularly cuts tens of megabytes. - Version and display your version: an app that cannot tell you which build it is makes bug reports useless.
- Sign your binaries for public distribution: an Authenticode or Apple Developer ID certificate is what stops the operating system from warning every user away.
- Ship an installer, not a bare exe, for non-technical users: Inno Setup or NSIS on Windows, a DMG on macOS — or let
briefcasedo it.
Practice Exercises
- The First Build: Package any Tkinter app you have written with
--onefile --windowed, then run the result from a folder that contains no Python source at all. Note the file size and the cold start-up time. - The Asset Bundle: Add an image to your app, load it via a
resource_pathhelper, and bundle it with--add-data. Deliberately break it first by using a plain relative path so you see the exact error your users would report. - The Diet Plan: Build the same app twice — once from your global Python environment and once from a clean virtualenv with only the needed packages. Compare the two output sizes, then add three
excludesto the.specand measure again.