SXXXXXXX_PyInstallerGUIWrapper/README.md
2025-05-06 14:56:23 +02:00

11 KiB

PyInstaller GUI Wrapper

English

PyInstaller GUI Wrapper is a user-friendly graphical interface designed to simplify the process of creating executable files from Python projects using PyInstaller. It streamlines the PyInstaller workflow, especially for projects following a specific folder structure, and automatically injects version information into the target application.

Features

  • Project-Based Approach: Instead of selecting individual scripts, you select a main project directory. The tool automatically detects:
    • The source code subfolder (expected to have the same name as the project directory, in lowercase).
    • The main entry point script (__main__.py) within the source subfolder.
    • The PyInstaller specification file (projectname.spec) in the project root.
    • An optional icon file (projectname.ico or similar) in the project root.
  • Automatic Version Injection:
    • If the target project directory is a Git repository, the wrapper extracts version information (tag, commit hash, branch, dirty status).
    • It automatically generates a _version.py file within the target project's source subfolder. This file contains the extracted Git information and a helper function get_version_string(format_string=None) to easily display formatted version details in the target application.
    • If the project is not a Git repository, default "unknown" values are used.
  • GUI for PyInstaller Options:
    • Manages common PyInstaller settings like one-file/one-dir mode, windowed/console application, application name, and icon.
    • Allows adding additional data files and folders to the bundle with relative path management.
  • Spec File Management:
    • Loads options from an existing .spec file if found.
    • GUI settings will override the .spec file, which is regenerated and saved before each build initiated from the GUI.
  • Real-time Build Log: Displays PyInstaller's output directly in the GUI during the build process.
  • Cross-Platform (Theoretically): Built with Tkinter, aiming for compatibility where Python and PyInstaller run.

How It Works (When Building a Target Project)

  1. Select Project Directory: Use the "Browse..." button to choose the root directory of the Python project you want to build.
  2. Path Derivation: The wrapper automatically looks for:
    • YourProjectRoot/yourprojectroot/__main__.py (main script)
    • YourProjectRoot/yourprojectroot.spec (PyInstaller spec file)
    • YourProjectRoot/yourprojectroot.ico (application icon - platform extensions may vary)
    • The GUI will indicate if these essential files are found.
  3. Version File Generation:
    • The wrapper checks if YourProjectRoot is a Git repository.
    • If yes, it extracts Git version details.
    • It then creates/overwrites YourProjectRoot/yourprojectroot/_version.py with this information and a get_version_string() helper function.
  4. Load/Configure Options:
    • If yourprojectroot.spec exists, its options are loaded into the GUI.
    • You can adjust PyInstaller settings (one-file, windowed, app name, icon, additional files) via the GUI.
  5. Build:
    • Click "Build Executable".
    • The wrapper generates/updates yourprojectroot.spec based on the current GUI settings.
    • PyInstaller is then executed using this spec file.
    • The build output (_dist/ and _build/ folders) will be created within YourProjectRoot.

Using the Generated _version.py in Your Target Application

After the PyInstaller GUI Wrapper builds your project, your target application's source folder (yourprojectroot/) will contain a _version.py file. You can use it like this:

# In your target application's main script or GUI module
# (e.g., yourprojectroot/__main__.py or yourprojectroot/app_gui.py)

try:
    from . import _version # Assuming _version.py is in the same package
    # or: from yourprojectroot import _version
except ImportError:
    # Fallback if _version.py is somehow missing
    class MockVersion:
        __version__ = "unknown"
        GIT_COMMIT_HASH = "N/A"
        GIT_BRANCH = "N/A"
        BUILD_TIMESTAMP = "N/A"
        IS_GIT_REPO = False
        def get_version_string(self, format_string=None):
            return "Version: Unknown (dev build)"
    _version = MockVersion()

# Example usage:
app_title = f"My Awesome App - {_version.get_version_string()}"
# or to get specific parts:
# commit_hash = _version.GIT_COMMIT_HASH
# build_date = _version.BUILD_TIMESTAMP.split('T')

# Example of custom format for get_version_string:
# custom_version_info = _version.get_version_string(
#     format_string="Tag: {{tag}}, Commit: {{commit_short}} on {{branch}} {{dirty}}"
# )
# print(custom_version_info)

Prerequisites

  • Python 3.x
  • PyInstaller (pip install pyinstaller)
  • Git (optional, but required for automatic version injection from Git repositories)

Running the PyInstaller GUI Wrapper

To run the PyInstaller GUI Wrapper itself (if you have cloned this repository):

python -m pyinstallerguiwrapper

You can also build an executable of the PyInstaller GUI Wrapper using the included pyinstallerguiwrapper.spec file by selecting its own root directory within the GUI.


Italiano

PyInstaller GUI Wrapper è un'interfaccia grafica intuitiva progettata per semplificare il processo di creazione di file eseguibili da progetti Python utilizzando PyInstaller. Ottimizza il flusso di lavoro di PyInstaller, specialmente per progetti che seguono una specifica struttura di cartelle, e inietta automaticamente le informazioni di versione nell'applicazione di destinazione.

Caratteristiche

  • Approccio Basato su Progetto: Invece di selezionare script individuali, si seleziona una directory di progetto principale. Lo strumento rileva automaticamente:
    • La sottocartella del codice sorgente (che si prevede abbia lo stesso nome della directory del progetto, in minuscolo).
    • Lo script di entry point principale (__main__.py) all'interno della sottocartella sorgente.
    • Il file di specifica PyInstaller (nomeprogetto.spec) nella root del progetto.
    • Un file icona opzionale (nomeprogetto.ico o simile) nella root del progetto.
  • Iniezione Automatica della Versione:
    • Se la directory del progetto di destinazione è un repository Git, il wrapper estrae le informazioni sulla versione (tag, hash del commit, branch, stato "dirty").
    • Genera automaticamente un file _version.py all'interno della sottocartella sorgente del progetto di destinazione. Questo file contiene le informazioni Git estratte e una funzione di supporto get_version_string(format_string=None) per visualizzare facilmente i dettagli della versione formattati nell'applicazione di destinazione.
    • Se il progetto non è un repository Git, vengono utilizzati valori predefiniti "unknown".
  • GUI per Opzioni PyInstaller:
    • Gestisce le impostazioni comuni di PyInstaller come la modalità file singolo/directory singola, applicazione con finestra/console, nome dell'applicazione e icona.
    • Permette di aggiungere file e cartelle di dati aggiuntivi al bundle con gestione dei percorsi relativi.
  • Gestione File Spec:
    • Carica le opzioni da un file .spec esistente, se trovato.
    • Le impostazioni della GUI sovrascriveranno il file .spec, che viene rigenerato e salvato prima di ogni build avviata dalla GUI.
  • Log di Build in Tempo Reale: Visualizza l'output di PyInstaller direttamente nella GUI durante il processo di build.
  • Multi-Piattaforma (Teoricamente): Costruito con Tkinter, mirando alla compatibilità dove Python e PyInstaller sono eseguibili.

Come Funziona (Quando si Compila un Progetto Target)

  1. Seleziona Directory Progetto: Usa il pulsante "Browse..." ("Sfoglia...") per scegliere la directory principale del progetto Python che vuoi compilare.
  2. Derivazione Percorsi: Il wrapper cerca automaticamente:
    • RootDelTuoProgetto/nomedeltuoprogetto/__main__.py (script principale)
    • RootDelTuoProgetto/nomedeltuoprogetto.spec (file spec di PyInstaller)
    • RootDelTuoProgetto/nomedeltuoprogetto.ico (icona dell'applicazione - le estensioni possono variare a seconda della piattaforma)
    • La GUI indicherà se questi file essenziali sono stati trovati.
  3. Generazione File di Versione:
    • Il wrapper controlla se RootDelTuoProgetto è un repository Git.
    • Se sì, estrae i dettagli della versione Git.
    • Quindi crea/sovrascrive RootDelTuoProgetto/nomedeltuoprogetto/_version.py con queste informazioni e una funzione di supporto get_version_string().
  4. Carica/Configura Opzioni:
    • Se nomedeltuoprogetto.spec esiste, le sue opzioni vengono caricate nella GUI.
    • Puoi regolare le impostazioni di PyInstaller (file singolo, con finestra, nome app, icona, file aggiuntivi) tramite la GUI.
  5. Build:
    • Clicca su "Build Executable" ("Crea Eseguibile").
    • Il wrapper genera/aggiorna nomedeltuoprogetto.spec in base alle impostazioni correnti della GUI.
    • PyInstaller viene quindi eseguito utilizzando questo file spec.
    • L'output della build (cartelle _dist/ e _build/) verrà creato all'interno di RootDelTuoProgetto.

Utilizzare il File _version.py Generato nella Tua Applicazione Target

Dopo che PyInstaller GUI Wrapper ha compilato il tuo progetto, la cartella sorgente della tua applicazione target (nomedeltuoprogetto/) conterrà un file _version.py. Puoi usarlo in questo modo:

# Nello script principale o nel modulo GUI della tua applicazione target
# (es. nomedeltuoprogetto/__main__.py o nomedeltuoprogetto/app_gui.py)

try:
    from . import _version # Assumendo che _version.py sia nello stesso package
    # oppure: from nomedeltuoprogetto import _version
except ImportError:
    # Fallback se _version.py dovesse mancare
    class MockVersion:
        __version__ = "unknown"
        GIT_COMMIT_HASH = "N/A"
        GIT_BRANCH = "N/A"
        BUILD_TIMESTAMP = "N/A"
        IS_GIT_REPO = False
        def get_version_string(self, format_string=None):
            return "Versione: Sconosciuta (build di sviluppo)"
    _version = MockVersion()

# Esempio di utilizzo:
titolo_app = f"La Mia Fantastica App - {_version.get_version_string()}"
# oppure per ottenere parti specifiche:
# commit_hash = _version.GIT_COMMIT_HASH
# data_build = _version.BUILD_TIMESTAMP.split('T')

# Esempio di formato personalizzato per get_version_string:
# info_versione_custom = _version.get_version_string(
#     format_string="Tag: {{tag}}, Commit: {{commit_short}} su {{branch}} {{dirty}}"
# )
# print(info_versione_custom)

Prerequisiti

  • Python 3.x
  • PyInstaller (pip install pyinstaller)
  • Git (opzionale, ma richiesto per l'iniezione automatica della versione da repository Git)

Eseguire PyInstaller GUI Wrapper

Per eseguire PyInstaller GUI Wrapper stesso (se hai clonato questo repository):

python -m pyinstallerguiwrapper

Puoi anche compilare un eseguibile di PyInstaller GUI Wrapper utilizzando il file pyinstallerguiwrapper.spec incluso, selezionando la sua stessa directory radice all'interno della GUI.