fix avvio senza finestra cmd-sh

This commit is contained in:
brontomark committed 2026-11-11 12:00:47 +01:00
1 parent f97a968c75
commit 48088c4a01
5 files changed
+117 -27

No files matched your search

+1
View File
@@ -15,6 +15,7 @@ server/venv_unix/
server/__pycache__/
server/build/
server/dist/
server/*.log
# OS
.DS_Store
+12 -5
View File
@@ -11,11 +11,18 @@ def get_launch_command() -> list[str]:
if getattr(sys, "frozen", False):
# Se compilato con PyInstaller
return [sys.executable, "--minimized"]
else:
# Se eseguito come script Python
python_exe = sys.executable
script_path = str(Path(__file__).parent / "main.py")
return [python_exe, script_path, "--minimized"]
# Se eseguito come script Python, preferisci pythonw.exe su Windows per evitare la finestra CMD
python_exe = sys.executable
if sys.platform == "win32":
exe_path = Path(sys.executable)
if exe_path.name.lower() == "python.exe":
pythonw_exe = exe_path.with_name("pythonw.exe")
if pythonw_exe.exists():
python_exe = str(pythonw_exe)
script_path = str(Path(__file__).resolve().parent / "main.py")
return [python_exe, script_path, "--minimized"]
def is_autostart_enabled() -> bool:
+2
View File
@@ -137,6 +137,8 @@ def build(windowed: bool = False) -> None:
output_bin = SERVER_DIR / "dist" / f"barcode_server{ext}"
print("\n[OK] Compilazione completata con successo!")
print(f"[OK] Eseguibile creato: {output_bin}")
if platform.system() == "Windows" and not windowed:
print("[i] Suggerimento: per un .exe Windows senza finestra CMD, usa: build_binary.py --windowed")
def main() -> None:
+61 -3
View File
@@ -20,8 +20,34 @@ from config import load_config
from server_core import BarcodeServerCore
def _configure_console_encoding() -> None:
"""Evita UnicodeEncodeError su console Windows legacy (cp1252/cp850)."""
def _configure_stdio() -> bool:
"""
Configura UTF-8 su console o reindirizza stdout/stderr su barcode_server.log
quando l'app e' avviata senza console (pythonw.exe o eseguibile --windowed).
Restituisce True se avviata in modalita' windowless (senza stdout/stderr nativi).
"""
is_windowless = sys.stdout is None or sys.stderr is None
if is_windowless:
log_handle = None
try:
from config import CONFIG_FILE
log_path = CONFIG_FILE.parent / "barcode_server.log"
log_path.parent.mkdir(parents=True, exist_ok=True)
if log_path.exists() and log_path.stat().st_size > 1_048_576:
log_path.write_text("", encoding="utf-8")
log_handle = open(log_path, "a", encoding="utf-8", errors="replace", buffering=1)
except Exception:
try:
log_handle = open(os.devnull, "w", encoding="utf-8")
except Exception:
log_handle = None
if sys.stdout is None and log_handle is not None:
sys.stdout = log_handle
if sys.stderr is None and log_handle is not None:
sys.stderr = log_handle
for stream in (sys.stdout, sys.stderr):
reconfigure = getattr(stream, "reconfigure", None)
if callable(reconfigure):
@@ -30,6 +56,31 @@ def _configure_console_encoding() -> None:
except Exception:
pass
return is_windowless
def _show_fatal_gui_error(message: str) -> None:
"""Mostra un avviso grafico se l'avvio windowless fallisce senza terminale visibile."""
try:
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.withdraw()
messagebox.showerror("Barcode Reader PC Server", message)
root.destroy()
return
except Exception:
pass
if sys.platform == "win32":
try:
import ctypes
ctypes.windll.user32.MessageBoxW(0, message, "Barcode Reader PC Server", 0x10)
except Exception:
pass
def print_ascii_qr(payload: str) -> None:
"""Stampa un codice QR leggibile direttamente nel terminale."""
@@ -100,7 +151,7 @@ def run_gui_mode(server: BarcodeServerCore, start_minimized: bool):
def main():
_configure_console_encoding()
is_windowless = _configure_stdio()
parser = argparse.ArgumentParser(description="Barcode Reader PC Server - Catelli Srl")
parser.add_argument(
"--cli", "--headless", "--no-gui",
@@ -131,6 +182,13 @@ def main():
except Exception as e:
import traceback
traceback.print_exc()
if is_windowless:
_show_fatal_gui_error(
f"Impossibile avviare l'interfaccia grafica del server:\n{e}\n\n"
"Controlla il file barcode_server.log per i dettagli."
)
sys.exit(1)
print(f"\n[!] Avviso: Impossibile avviare interfaccia grafica ({e}). Fallback su modalità terminale.")
if "tkinter" in str(e).lower() or "libtk" in str(e).lower() or isinstance(e, ImportError):
print("\n[i] NOTA PER LINUX:")
+41 -19
View File
@@ -22,8 +22,7 @@ if not defined PY_CMD (
echo.
echo [!] Python 3.9 o superiore ^(con modulo venv^) non trovato.
echo Assicurati di aver installato Python da https://www.python.org/downloads/windows/
echo e di aver selezionato "Add python.exe to PATH" durante l'installazione.
echo ^(Se hai solo lo stub del Microsoft Store, installa Python ufficiale o dal Store.^)
echo oppure dal Microsoft Store, e verifica con: py -3 --version
echo.
popd
pause
@@ -39,6 +38,7 @@ if exist "venv\bin" (
)
set "VENV_PY=%VENV_DIR%\Scripts\python.exe"
set "VENV_PYW=%VENV_DIR%\Scripts\pythonw.exe"
if not exist "%VENV_PY%" (
echo [+] Creazione ambiente virtuale Python in "%VENV_DIR%"...
%PY_CMD% -m venv "%VENV_DIR%"
@@ -50,23 +50,47 @@ if not exist "%VENV_PY%" (
)
)
echo [+] Verifica dipendenze...
"%VENV_PY%" -m pip install --disable-pip-version-check -q -r requirements.txt
"%VENV_PY%" -c "import aiohttp, pynput, pyperclip, qrcode, pystray, PIL" >nul 2>&1
if errorlevel 1 (
echo [!] Errore durante l'installazione delle dipendenze da requirements.txt.
popd
pause
exit /b 1
echo [+] Installazione dipendenze da requirements.txt...
"%VENV_PY%" -m pip install --disable-pip-version-check -q -r requirements.txt
if errorlevel 1 (
echo [!] Errore durante l'installazione delle dipendenze da requirements.txt.
popd
pause
exit /b 1
)
)
"%VENV_PY%" -c "import tkinter" >nul 2>&1
if errorlevel 1 (
echo ------------------------------------------------------------------
echo [!] ATTENZIONE: Tkinter non risulta installato in questo Python.
echo L'applicazione fara' fallback sulla modalita' terminale ^(CLI^).
echo Per avere la GUI e la Tray Icon, reinstalla Python includendo
echo l'opzione "tcl/tk and IDLE".
echo ------------------------------------------------------------------
set "FORCE_CONSOLE=0"
for %%A in (%*) do (
if /i "%%~A"=="--cli" set "FORCE_CONSOLE=1"
if /i "%%~A"=="--headless" set "FORCE_CONSOLE=1"
if /i "%%~A"=="--no-gui" set "FORCE_CONSOLE=1"
if /i "%%~A"=="-h" set "FORCE_CONSOLE=1"
if /i "%%~A"=="--help" set "FORCE_CONSOLE=1"
)
if "%FORCE_CONSOLE%"=="0" (
"%VENV_PY%" -c "import tkinter" >nul 2>&1
if errorlevel 1 (
echo ------------------------------------------------------------------
echo [!] ATTENZIONE: Tkinter non risulta installato in questo Python.
echo L'applicazione fara' fallback sulla modalita' terminale ^(CLI^).
echo Per avere la GUI e la Tray Icon, reinstalla Python includendo
echo l'opzione "tcl/tk and IDLE".
echo ------------------------------------------------------------------
set "FORCE_CONSOLE=1"
)
)
if "%FORCE_CONSOLE%"=="0" (
if exist "%VENV_PYW%" (
start "" "%VENV_PYW%" main.py %*
popd
exit /b 0
)
echo [!] pythonw.exe non trovato in "%VENV_DIR%\Scripts": avvio con console aperta.
)
"%VENV_PY%" main.py %*
@@ -76,10 +100,8 @@ popd
if not "%APP_EXIT%"=="0" (
echo.
echo [!] Il server e' terminato con codice %APP_EXIT%.
pause
) else (
pause
)
pause
exit /b %APP_EXIT%
:try_python