155 lines
5.0 KiB
Python
Executable File
155 lines
5.0 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""
|
|
Script per creare un eseguibile standalone (Windows .exe, Linux binary, macOS binary)
|
|
con PyInstaller in un singolo file, usando automaticamente un ambiente virtuale locale.
|
|
"""
|
|
|
|
import argparse
|
|
import os
|
|
from pathlib import Path
|
|
import platform
|
|
import subprocess
|
|
import sys
|
|
|
|
|
|
SERVER_DIR = Path(__file__).resolve().parent
|
|
|
|
HIDDEN_IMPORTS = [
|
|
"pystray",
|
|
"PIL",
|
|
"PIL.ImageTk",
|
|
"PIL._tkinter_finder",
|
|
"qrcode",
|
|
"aiohttp",
|
|
"pynput",
|
|
]
|
|
|
|
|
|
def _configure_console_encoding() -> None:
|
|
"""Forza stdout/stderr in UTF-8 per evitare errori su console Windows cp1252."""
|
|
for stream in (sys.stdout, sys.stderr):
|
|
if stream is not None and hasattr(stream, "reconfigure"):
|
|
try:
|
|
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _venv_python(venv_dir: Path) -> Path:
|
|
if platform.system() == "Windows":
|
|
return venv_dir / "Scripts" / "python.exe"
|
|
python_bin = venv_dir / "bin" / "python"
|
|
if python_bin.exists():
|
|
return python_bin
|
|
return venv_dir / "bin" / "python3"
|
|
|
|
|
|
def _resolve_venv_dir(base_dir: Path) -> Path:
|
|
default_venv = base_dir / "venv"
|
|
if platform.system() == "Windows":
|
|
if (default_venv / "bin").exists() and not (default_venv / "Scripts" / "python.exe").exists():
|
|
print('[!] Rilevato ambiente virtuale Unix in "venv". Uso "venv_win".')
|
|
return base_dir / "venv_win"
|
|
return default_venv
|
|
|
|
has_unix_python = (default_venv / "bin" / "python").exists() or (default_venv / "bin" / "python3").exists()
|
|
if (default_venv / "Scripts").exists() and not has_unix_python:
|
|
print('[!] Rilevato ambiente virtuale Windows in "venv". Uso "venv_unix".')
|
|
return base_dir / "venv_unix"
|
|
return default_venv
|
|
|
|
|
|
def _can_import(python_exe: Path, module_name: str) -> bool:
|
|
result = subprocess.run(
|
|
[str(python_exe), "-c", f"import {module_name}"],
|
|
stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.DEVNULL,
|
|
)
|
|
return result.returncode == 0
|
|
|
|
|
|
def _ensure_venv_python(base_dir: Path) -> Path:
|
|
# Se gia' dentro un virtualenv attivo, usa quell'interprete senza annidare venv.
|
|
if sys.prefix != getattr(sys, "base_prefix", sys.prefix):
|
|
return Path(sys.executable)
|
|
|
|
venv_dir = _resolve_venv_dir(base_dir)
|
|
venv_python = _venv_python(venv_dir)
|
|
if not venv_python.exists():
|
|
print(f"[+] Creazione ambiente virtuale Python in {venv_dir.name}...")
|
|
subprocess.check_call([sys.executable, "-m", "venv", str(venv_dir)])
|
|
return venv_python
|
|
|
|
|
|
def _ensure_build_dependencies(venv_python: Path) -> None:
|
|
print("[+] Verifica dipendenze in requirements.txt...")
|
|
subprocess.check_call(
|
|
[str(venv_python), "-m", "pip", "install", "--disable-pip-version-check", "-q", "-r", "requirements.txt"]
|
|
)
|
|
|
|
if not _can_import(venv_python, "PyInstaller"):
|
|
print("[!] PyInstaller non installato nel venv. Installazione in corso...")
|
|
subprocess.check_call(
|
|
[str(venv_python), "-m", "pip", "install", "--disable-pip-version-check", "pyinstaller"]
|
|
)
|
|
|
|
|
|
def _warn_if_tkinter_missing(venv_python: Path) -> None:
|
|
if _can_import(venv_python, "tkinter"):
|
|
return
|
|
|
|
print("[!] ATTENZIONE: Tkinter non trovato in questo Python.")
|
|
print(" L'eseguibile compilato funzionera' solo in modalita' CLI (--cli).")
|
|
if platform.system() == "Linux":
|
|
print(" Per includere anche la GUI, installa tk (es. sudo pacman -S tk / sudo apt install python3-tk).")
|
|
elif platform.system() == "Windows":
|
|
print(" Reinstalla Python assicurandoti di includere 'tcl/tk and IDLE'.")
|
|
|
|
|
|
def build(windowed: bool = False) -> None:
|
|
_configure_console_encoding()
|
|
os.chdir(SERVER_DIR)
|
|
|
|
print(f"[+] Compilazione eseguibile per {platform.system()}...")
|
|
venv_python = _ensure_venv_python(SERVER_DIR)
|
|
_ensure_build_dependencies(venv_python)
|
|
_warn_if_tkinter_missing(venv_python)
|
|
|
|
cmd = [
|
|
str(venv_python),
|
|
"-m",
|
|
"PyInstaller",
|
|
"--name=barcode_server",
|
|
"--onefile",
|
|
"--clean",
|
|
"--noconfirm",
|
|
]
|
|
if windowed:
|
|
cmd.append("--windowed")
|
|
for hidden_import in HIDDEN_IMPORTS:
|
|
cmd.append(f"--hidden-import={hidden_import}")
|
|
cmd.append("main.py")
|
|
|
|
print(f"[+] Comando: {' '.join(cmd)}")
|
|
subprocess.check_call(cmd)
|
|
|
|
ext = ".exe" if platform.system() == "Windows" else ""
|
|
output_bin = SERVER_DIR / "dist" / f"barcode_server{ext}"
|
|
print("\n[OK] Compilazione completata con successo!")
|
|
print(f"[OK] Eseguibile creato: {output_bin}")
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description="Compila barcode_server in un eseguibile standalone")
|
|
parser.add_argument(
|
|
"--windowed",
|
|
action="store_true",
|
|
help="Compila senza finestra terminale (GUI/Tray only; su --cli non mostrera' output su Windows)",
|
|
)
|
|
args = parser.parse_args()
|
|
build(windowed=args.windowed)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|