Anatomy of the --onefile vs. --onedir Bundle and the Size Myth
When you pass --onefile to PyInstaller, the build tool does not strip dead code, prune unused shared libraries, or shrink your Python interpreter. Instead, the bootloader appends a compressed archive (typically using zlib or LZMA) containing the exact same set of .pyc bytecode files, .so/.dll shared objects, and data assets that a --onedir build places into a directory tree. If your bundle contains a 600 MB scientific or machine learning stack, --onefile still carries all 600 MB of underlying payload inside that single executable. Any file-size reduction you observe on disk comes from archive compression ratios minus a small bootloader stub, whereas at runtime the uncompressed bytes must be written out anyway—meaning --onefile often inflates temporary storage pressure rather than saving space.
The physical cause of tmpfs failures lies in how a --onefile binary boots. When launched, the C bootloader reads the embedded archive, decompresses each entry, and writes the unpacked files into a temporary directory—commonly under /tmp or TMPDIR—before loading the embedded Python runtime from those extracted files. Because tmpfs stores files in page cache backed by system RAM and swap rather than a persistent block device, every decompressed byte occupies volatile memory pages or hits a strict tmpfs size cap (such as a container's default 64 MB /dev/shm or tight /tmp mount). As decompressed bytes accumulate in tmpfs, free memory pages shrink or the mount hits its quota; once exhausted, the write syscall fails with ENOSPC (no space left on device) or the kernel's out-of-memory (OOM) killer terminates the process.
Startup latency follows a parallel mechanical chain. Under --onefile, cold start requires sequential decompression and filesystem writes of potentially hundreds of megabytes into the temporary directory on every invocation, followed by dynamic linker symbol resolution and Python imports. Under --onedir, the files already sit unpacked on disk or in an existing directory, so launching skips the full-bundle decompression-and-extraction pass and goes straight to loading shared libraries and executing Python code. However, --onedir is not universally faster: if a network filesystem has high metadata latency across thousands of small files, or if a warm tmpfs page cache already holds the extracted payload while cold storage is slow, those local I/O dynamics can shift the balance.
Decision Dominance: Choosing Between --onedir and --onefile
- Optimal default for tmpfs-constrained and production runtimes:
--onedir. By eliminating runtime self-extraction into volatile temporary storage,--onediravoidsENOSPCquota exhaustion and avoids duplicating payload bytes across both archive/page cache and extracted files in RAM-backedtmpfs. It is strictly more reliable than--onefilewhen temporary space is bounded or memory is tight. - When
--onedirstops working: When the deployment target only permits distributing a single standalone binary file with no directory bundle or archive wrapper allowed, or when the target filesystem has severe per-file open/stat overhead across thousands of tiny dependency files and cannot be pre-staged. - Typical choice errors and their mechanism: Engineers frequently pick
--onefileassuming single-file packaging shrinks the application, when in reality compression only trades CPU decompression time for a smaller transfer artifact while expanding back to full size intmpfsat runtime. Another common mistake is pointingTMPDIRat a largertmpfsmount without checking total system RAM: expandingtmpfscapacity without sufficient backing RAM/swap simply allows a giant extraction to push the host closer to OOM eviction. - Selection rule: If
/tmporTMPDIRis backed by memory-cappedtmpfs, or if cold-start speed and predictable memory headroom matter more than a single-file artifact -> use--onedir. Only use--onefilewhen a single-file executable is a hard distribution requirement and the target environment has ample temporary storage and RAM headroom to absorb full decompression on every launch.
Why --onefile Breaks on tmpfs: Extraction, Memory, and Execution Constraints
When a PyInstaller --onefile executable launches, a compiled C bootloader opens its own binary image, locates the trailing archive appended during build, decompresses entries (typically zlib or LZMA), and writes every extracted file into a temporary directory under TMPDIR or /tmp before starting the embedded Python runtime. When that target directory sits on a tmpfs mount, those writes do not hit a disk block layer; they allocate kernel page cache backed by physical RAM and swap. Switching to --onedir eliminates this runtime extraction phase because the bootloader loads pre-unpacked .pyc bytecode, shared libraries, and data files directly from disk rather than materializing a second copy in volatile memory.
A common assumption is that --onefile shrinks an application because it produces a single file. It does not prune unused modules, strip dead bytecode, or shrink shared libraries; it packages the same dependency graph as --onedir inside a compressed container plus a bootloader stub. Any file-size reduction comes strictly from archive compression minus bootloader overhead, while runtime execution still inflates the uncompressed payload.
Core Failure Mechanics on tmpfs
- Mount cap exhaustion (ENOSPC): Each extracted file written to a size-capped tmpfs mount consumes filesystem blocks out of the mount's configured capacity limit. Once uncompressed bytes plus filesystem metadata exceed that cap, the kernel rejects further write syscalls with ENOSPC, aborting bootloader extraction before Python starts.
- Page-cache and RAM pressure (OOM killer): Because tmpfs stores file contents in memory pages rather than persistent blocks, extracting a large scientific or AI bundle expands anonymous/page-cache memory usage while the Python process simultaneously allocates heap for interpreters and loaded .so libraries. When total memory and swap demand crosses the cgroup or system limit, the kernel out-of-memory (OOM) killer terminates the process.
- Noexec and permission enforcement: Bootloaders unpack shared libraries and helper binaries into the temp directory and invoke dynamic linking or execution against those extracted paths. If the tmpfs mount carries noexec or restricted permissions, loading shared objects or executing extracted binaries fails at the kernel/loader boundary even when free space and RAM remain available.
- Cold-start extraction latency: Every cold launch of a --onefile binary repeats archive scanning, decompression CPU work, and temp-directory file creation before symbol resolution and module imports even begin. A --onedir build bypasses decompression and write amplification on launch, moving straight to opening existing files.
Five Deployment Scenarios Where --onefile Fails
| Deployment Scenario | Physical Constraint | Causal Failure Chain | Observable Effect |
| Restricted container /tmp | Capped tmpfs on /tmp with tight container memory limit | Bootloader decompresses bundle into /tmp -> page cache fills capped tmpfs or pushes cgroup memory to limit -> write returns ENOSPC or cgroup OOM kills task | Immediate startup crash with extraction write error or silent exit code 137 |
| Shared-memory /tmp mapped to /dev/shm | /tmp symlinked or bound to small /dev/shm segment | Unpacked shared libraries and data exceed small shared-memory cap -> page allocation hits segment ceiling -> archive unpack halts mid-stream | Partial temp folder and failed PyInstaller bootloader extraction error |
| Hardened Linux runtime with noexec /tmp | tmpfs mounted with noexec (and sometimes nosuid/nodev) | Bootloader writes .so or binary payloads to /tmp -> dlopen or execve hits noexec mount flag -> kernel blocks code execution | Dynamic linker or permission/execution failure during runtime initialization |
| High-concurrency worker autoscaling | Multiple --onefile workers starting simultaneously on one host | Concurrent processes decompress duplicate bundles into tmpfs -> multiplied page-cache footprint and CPU decompression contention -> memory exhausts host RAM/swap | Cascading OOM kills and multi-second startup spikes across workers |
| Low-RAM embedded or edge Linux node | Limited physical RAM with little or no swap | Decompressed payload plus Python/ML runtime heap exceeds physical page frames -> memory reclaim cannot free pinned/active pages -> kernel OOM killer triggers | Process killed mid-import or right after extraction completes |
--onedir vs. --onefile: Effectiveness and Edge Cases
--onedir is the optimal default for server, container, and edge deployments. By keeping files unpacked in a directory, it removes per-launch decompression work, avoids duplicate byte materialization inside tmpfs, and makes memory consumption much more predictable. It also matches actual on-disk payload reality: a 600 MB scientific or AI stack is roughly 600 MB of actual code, libraries, and data either way, so --onefile is trading startup time and runtime memory/temp overhead for single-file convenience rather than shrinking the real application footprint.
Even --onedir stops working cleanly under specific edge conditions. If a distribution pipeline strictly mandates a single standalone binary with zero supporting directories or wrapper scripts, --onedir does not meet that packaging constraint. In addition, when a --onedir bundle containing thousands of small files sits on a high-metadata-latency network filesystem without pre-staging, repeated open and stat round-trips across many tiny files can slow startup, whereas a warm tmpfs page cache or slow cold storage can invert relative I/O costs between the two modes.
Typical Choice Errors and Selection Rule
- Treating --onefile as a footprint shrinker: Teams often pick --onefile expecting a smaller app, overlooking that archive compression only packs the same underlying dependencies on disk while unpacking them back into memory or temp storage at runtime.
- Raising tmpfs size without RAM/swap headroom: Increasing a tmpfs TMPDIR limit lets extraction write more bytes into page cache, which removes ENOSPC only to push total memory usage past physical RAM and swap into an OOM kill.
- Pointing TMPDIR at a noexec mount: Redirecting TMPDIR to another tmpfs volume without checking mount flags can still block shared-library loading if noexec is set.
Decision rule: If /tmp or TMPDIR is backed by a memory-capped tmpfs, or if cold-start speed and predictable RAM headroom matter more than a single file, use --onedir; use --onefile only when a hard single-file requirement applies and temp storage plus RAM/swap have enough headroom for full per-launch extraction.
Fixing PyInstaller --onefile tmpfs Issues by Switching to --onedir and Clarifying Size Myths
When a Python service or CLI tool built with PyInstaller --onefile starts failing inside containers, restricted Linux pods, or low-memory nodes, the culprit is almost always how the bootloader handles temporary storage on tmpfs. Switching from --onefile to --onedir is the right fix in most server and container environments. It eliminates per-launch extraction onto memory-backed temporary filesystems, cuts cold-start overhead, and preserves predictable memory headroom without actually costing you real-world application size.
A common misconception is that --onefile shrinks your application. It does not prune unused imports, strip dead bytecode, or drop shared libraries from your dependency graph. It takes the exact same set of .pyc files, .so or .dll shared objects, and data files that --onedir places into a folder, compresses them into a trailing archive (typically zlib or LZMA), and attaches a C bootloader stub. If your scientific or AI stack unpacks to 600 MB, all 600 MB of underlying code and libraries still exist inside the single binary. The single executable looks smaller on disk only because the archive is compressed minus the bootloader stub's bytes; the moment it runs, those compressed bytes must be decompressed and written back out in uncompressed form.
Why --onefile Breaks on tmpfs
Unlike a persistent block device such as an ext4 or XFS disk partition, tmpfs stores files in volatile page cache backed by physical RAM and swap. When a --onefile binary launches, its C bootloader reads its own trailing archive, decompresses entries in sequence, and writes the unpacked files into a temporary directory under TMPDIR or /tmp before starting the embedded Python runtime.
- Mount cap exhaustion (ENOSPC): Writing uncompressed shared libraries and assets into a size-capped tmpfs mount allocates page cache entries against that mount limit. Once the unpacked payload plus filesystem metadata hits the cap, the kernel rejects subsequent write syscalls with ENOSPC, aborting startup before Python imports even begin.
- RAM and swap pressure (OOM killer): Every byte written to tmpfs consumes memory pages alongside the Python interpreter heap, NumPy or PyTorch allocations, and mapped shared libraries. When combined page cache and process memory cross a cgroup limit or host RAM-plus-swap capacity, memory reclaim cannot free enough clean pages fast enough, and the Linux OOM killer terminates the process (often surfacing as exit code 137).
- Hardened mount permissions (noexec): Security-hardened containers frequently mount /tmp or TMPDIR with noexec (often paired with nosuid and nodev). Even when free space and RAM are plentiful, extracting .so libraries or helper binaries into a noexec mount causes dynamic linking (dlopen) or execution (execve) to fail with permission errors because the kernel blocks code execution from that mount.
- Concurrent worker spikes: Scaling out multiple --onefile workers on one host triggers simultaneous archive decompression and page-cache growth across processes, compounding CPU load and pushing shared RAM/swap into contention or OOM kills.
Comparative Trade-Offs: Reliability, Startup Latency, and Operational Overhead
Choosing between --onedir and --onefile is an operational trade-off between single-artifact convenience and runtime determinism. Once unpacked, both modes load shared objects and execute Python bytecode in the same general runtime model, but --onefile pays an extraction tax on every cold start while competing for tmpfs memory.
- Containerization and memory predictability: In Docker or Kubernetes, --onedir copies a pre-unpacked directory into the container image layer once at build time. At runtime, shared libraries and data files are read straight from the container filesystem rather than duplicated into a memory-capped tmpfs /tmp or /dev/shm. That keeps memory usage much more predictable under tight cgroup limits.
- CI/CD and artifact distribution: --onefile wins on raw distribution simplicity when you must ship a single standalone file over a basic upload step, copy it to an air-gapped target, or hand a single binary to users without packaging a tarball or zip archive. --onedir requires archiving and unpacking a directory (such as a .tar.gz) in your build and deploy pipeline, adding a small packaging step in CI/CD so runtime hosts do not have to unpack on every launch.
- Filesystem permissions and hardening: Because --onedir lives in a known application directory (for example, /opt/app) rather than extracting executables into /tmp at runtime, it avoids noexec failures on /tmp and makes file ownership and read/execute permissions explicit at deploy time.
- Cold-start speed: Every --onefile cold launch must scan the archive, run decompression CPU cycles, and create temporary files before Python starts importing modules. --onedir skips full-bundle extraction and goes straight to opening existing files and resolving symbols, making cold starts faster in standard local and container setups.
Edge Cases and Failure Modes of --onedir
--onedir is not immune to environmental bottlenecks. If you place a large --onedir bundle containing thousands of small .pyc and dependency files onto a high-metadata-latency network filesystem (such as certain remote NFS or shared mounts) without pre-staging locally, repeated open and stat calls during Python startup can introduce noticeable latency—sometimes enough to invert the usual startup advantage over a warm tmpfs cache. It also falls short whenever a distribution policy strictly forbids a directory bundle or wrapper script.
Engineers running into --onefile tmpfs errors frequently make three mechanical mistakes: treating --onefile as if it shrinks runtime memory or dependency size; enlarging a tmpfs TMPDIR limit without adding backing RAM or swap (which simply shifts failures from ENOSPC to OOM kills); or pointing TMPDIR to another tmpfs path without checking whether noexec is set.
Decision Rule
If /tmp or TMPDIR sits on a memory-capped tmpfs, or if cold-start speed and predictable RAM headroom matter more than shipping a single file, use --onedir. Use --onefile only when a strict single-file requirement applies and the target host has enough temporary storage, non-noexec permissions, and RAM/swap headroom to absorb full decompression on every launch.
Why --onedir Beats --onefile on tmpfs and What --onefile Actually Shrinks
When a PyInstaller --onefile binary fails on tmpfs, the failure is not a quirk of PyInstaller being picky about temporary folders—it is a resource collision between archive decompression and memory-backed filesystem allocation. Switching to --onedir is the right move for servers, containers, and edge runtimes because it eliminates per-launch self-extraction, keeps memory consumption predictable, and exposes the true uncompressed size of your application rather than hiding it behind a zip or LZMA wrapper.
A common myth is that --onefile shrinks the application. It does not prune unused imports, strip dead bytecode, or drop heavy scientific or AI libraries from the dependency graph. It packs the exact same .pyc files, shared libraries (.so or .dll), and data assets into a compressed archive appended to a C bootloader stub. On disk, the single binary looks smaller only because archive compression (such as zlib or LZMA) squeezes repetitive bytes minus the bootloader overhead. At runtime, the bootloader still decompresses that payload and writes the full unpacked tree to disk before embedded Python starts. A 600 MB scientific or numerical stack is still 600 MB of code and libraries once materialized.
How --onefile Breaks tmpfs and Inflates Startup Latency
Unlike a persistent block device such as ext4 or XFS, tmpfs stores files in volatile kernel page cache backed by physical RAM and swap. When a --onefile process launches, its C bootloader reads the trailing archive, decompresses entries sequentially, and issues write syscalls into TMPDIR (often /tmp) before Python imports begin. Each causal failure chain traces directly to that extraction step:
- Mount cap exhaustion (ENOSPC): Sequential decompression writes uncompressed files plus filesystem metadata into tmpfs page cache -> allocated pages reach the tmpfs size cap -> subsequent write syscalls fail with ENOSPC -> startup aborts before Python initializes.
- RAM and swap pressure (OOM killer, exit code 137): Decompressed tmpfs pages expand concurrently with the Python heap, numerical or ML array allocations, and mapped shared libraries -> total anonymous and page-cache memory crosses the cgroup or host RAM-plus-swap ceiling faster than page reclaim can free clean or movable pages -> the Linux OOM killer terminates the process with exit code 137.
- Hardened mount enforcement (noexec): Security-hardened hosts mount /tmp or TMPDIR with noexec (often alongside nosuid and nodev) -> the bootloader extracts .so libraries or helper binaries into that directory, then calls dlopen or execve -> the kernel blocks execution on the noexec mount despite free space and free RAM -> dynamic linking or binary launch fails immediately.
- Concurrent worker spikes: Multiple --onefile workers start on the same host simultaneously -> parallel decompression multiplies CPU load while multiple tmpfs directories expand page cache at once -> host memory pressure spikes and triggers cascading OOM kills or multi-second startup stalls.
- Cold-start overhead: Every cold launch repeats archive scanning, decompression CPU cycles, and temp-file creation before module imports even start, whereas --onedir opens pre-extracted files directly.
Decision Framework and Migration Checklist for Moving to --onedir
Between the two modes, --onedir is the superior default whenever you control the runtime environment, care about cold-start speed, or run inside memory-constrained containers and edge nodes. It places pre-unpacked files in an explicit directory (such as /opt/app) with deterministic ownership and permissions, avoiding tmpfs bloat and /tmp noexec traps.
--onedir stops working cleanly under two clear conditions: first, when distribution policy or packaging rules strictly require a single standalone executable with no supporting directory or wrapper; second, when a bundle containing thousands of small files is placed directly on a high-latency network filesystem (such as remote NFS) without local staging, where thousands of open and stat round-trips can make startup slower than unpacking into a warm local cache.
Engineers frequently make three avoidable mistakes when troubleshooting --onefile tmpfs failures. First, they assume --onefile reduces runtime RAM or trims unused dependencies, ignoring that unpacked artifacts still enter memory or page cache. Second, they enlarge the tmpfs size cap without adding backing RAM or swap, which merely trades an ENOSPC write error for an OOM kill when memory fills. Third, they point TMPDIR at another tmpfs mount without checking whether noexec is set, leaving dlopen and execve blocked.
Selection rule: If /tmp or TMPDIR sits on a memory-capped tmpfs, or if cold-start latency, predictable cgroup memory headroom, and explicit file permissions matter most, use --onedir. Use --onefile only when a strict single-file requirement applies and the target host provides enough temporary storage, non-noexec permissions, and RAM-plus-swap headroom for full decompression on every launch.
If --onefile must stay in place temporarily, contain the blast radius by setting TMPDIR to a non-noexec persistent or local scratch path with verified free space, sizing RAM and swap above peak unpacked payload plus runtime heap, and staging concurrent worker starts rather than launching dozens in lockstep.
- Switch the build spec to --onedir: Update your PyInstaller build command or .spec file from --onefile to --onedir and inspect the actual uncompressed directory size and largest dependencies.
- Package and transfer as an archive: Bundle the output directory (for example, with tar.gz) in CI/CD so artifacts move cleanly between build stages, registries, or release hosts.
- Install into a non-tmpfs directory with explicit permissions: Extract the bundle into a persistent path such as /opt/app (or bake it into the container image layer at build time) with explicit read/execute permissions and ownership rather than relying on /tmp.
- Avoid high-latency network mounts for raw --onedir trees: If deploying to network storage, copy or unpack onto local disk or container storage before execution rather than serving thousands of small files over a high-latency share.
- Verify cold-start latency and cgroup memory under concurrency: Benchmark startup time and peak RSS/cgroup memory with realistic worker concurrency, confirming tmpfs usage stays flat and exit code 137 OOM kills disappear.

