46 lines
1.8 KiB
Python
46 lines
1.8 KiB
Python
"""Resolve where the application's own files live at runtime.
|
|
|
|
Three ways this app can run, all needing the *same* relative layout
|
|
(``i18n/<lang>/...`` and ``app/styles.tcss`` next to ``main.py``) to be
|
|
discoverable as real files on disk:
|
|
|
|
* **Plain source checkout** — ``python main.py``. Everything is exactly
|
|
where it looks in this repository.
|
|
* **PyInstaller onefile build** — the interpreter, bundled packages and
|
|
``--add-data`` files are unpacked into a temporary directory at startup,
|
|
exposed as ``sys._MEIPASS``. Pure-Python modules (like this one) run
|
|
from a synthetic, non-existent path, but explicitly added data files
|
|
(``i18n/`` and ``app/styles.tcss``) are real files under ``_MEIPASS``.
|
|
* **pex zipapp** — pex extracts its bundled sources to a cache directory
|
|
on first run and imports them from there, so ``__file__``-based
|
|
resolution behaves exactly like the plain source checkout.
|
|
|
|
:func:`bundle_root` returns the single directory to resolve both cases
|
|
against, so callers don't need to know which one they're running under.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def is_frozen() -> bool:
|
|
"""True inside a PyInstaller-built executable."""
|
|
return bool(getattr(sys, "frozen", False))
|
|
|
|
|
|
def bundle_root() -> Path:
|
|
"""Directory that contains ``i18n/`` and ``app/`` at runtime."""
|
|
if is_frozen():
|
|
meipass = getattr(sys, "_MEIPASS", None)
|
|
if meipass:
|
|
return Path(meipass)
|
|
# Onedir builds without _MEIPASS (shouldn't normally happen with
|
|
# the bundled spec, but fall back to the executable's directory).
|
|
return Path(sys.executable).resolve().parent
|
|
|
|
# Plain source checkout or a pex zipapp: this file lives at
|
|
# <project_root>/app/runtime_paths.py.
|
|
return Path(__file__).resolve().parent.parent
|