[Python] Getting version number from dynamic versioning inside exe

Discussão em 'Python' iniciado por Stack, Julho 3, 2025.

  1. Stack

    Stack Membro Participativo

    I have a project set up with automatic versioning with setuptools_scm. I also configured it to write the version to a version file and added the file path to the .spec file for building. The version is displayed in the title of a PyQt window, but this only works properly when running it from the development environment. Somehow I cannot get it to work from inside the executable. I've tried asking Github Copilot, ChatGPT and Copilot for fixes, but nothing seems to work.

    What is the proper way to auto-generate version numbers from the Git tag and have it available inside an executable?

    def get_app_version() -> str:
    """
    Simple version detection: check for __version__ in _version.py.
    Returns:
    str: version string (e.g. '1.2.3', 'not_found', or 'bad')
    """
    import os
    import importlib.util
    import sys
    possible_paths = []
    if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
    # Check both root and package subdir in the PyInstaller bundle
    possible_paths.append(os.path.join(sys._MEIPASS, "_version.py"))
    possible_paths.append(os.path.join(sys._MEIPASS, "package_name", "_version.py"))
    possible_paths.append(os.path.join(os.path.dirname(sys.executable), "_version.py"))
    possible_paths.append(os.path.join(os.path.dirname(sys.executable), "package_name", "_version.py"))
    else:
    possible_paths.append(os.path.join(os.path.dirname(__file__), "_version.py"))
    possible_paths.append(os.path.join(os.getcwd(), "_version.py"))
    for version_path in possible_paths:
    if os.path.exists(version_path):
    try:
    spec = importlib.util.spec_from_file_location("_version", version_path)
    _version = importlib.util.module_from_spec(spec)
    sys.modules["_version"] = _version
    spec.loader.exec_module(_version)
    version = getattr(_version, "__version__", None)
    if version is None:
    return "not_found"
    if not isinstance(version, str) or not version.strip():
    return "bad"
    return version
    except Exception:
    return "bad"
    return "not_found"

    Continue reading...

Compartilhe esta Página