fix server
This commit is contained in:
1 parent
7bf0ae9725
commit
f97a968c75
7 files changed
+266
-34
No files matched your search
@@ -10,6 +10,8 @@ dist/
|
||||
*.egg-info/
|
||||
.pytest_cache/
|
||||
server/venv/
|
||||
server/venv_win/
|
||||
server/venv_unix/
|
||||
server/__pycache__/
|
||||
server/build/
|
||||
server/dist/
|
||||
|
||||
@@ -6,7 +6,7 @@ a = Analysis(
|
||||
pathex=[],
|
||||
binaries=[],
|
||||
datas=[],
|
||||
hiddenimports=['pystray', 'PIL', 'qrcode', 'aiohttp'],
|
||||
hiddenimports=['pystray', 'PIL', 'PIL.ImageTk', 'PIL._tkinter_finder', 'qrcode', 'aiohttp', 'pynput'],
|
||||
hookspath=[],
|
||||
hooksconfig={},
|
||||
runtime_hooks=[],
|
||||
|
||||
+128
-16
@@ -1,42 +1,154 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Script per creare un eseguibile standalone (Windows .exe, Linux binary, macOS binary)
|
||||
con PyInstaller in un singolo file.
|
||||
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
|
||||
|
||||
|
||||
def build():
|
||||
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()}...")
|
||||
try:
|
||||
import PyInstaller
|
||||
except ImportError:
|
||||
print("[!] PyInstaller non installato. Installazione in corso...")
|
||||
subprocess.check_call([sys.executable, "-m", "pip", "install", "pyinstaller"])
|
||||
venv_python = _ensure_venv_python(SERVER_DIR)
|
||||
_ensure_build_dependencies(venv_python)
|
||||
_warn_if_tkinter_missing(venv_python)
|
||||
|
||||
cmd = [
|
||||
sys.executable,
|
||||
str(venv_python),
|
||||
"-m",
|
||||
"PyInstaller",
|
||||
"--name=barcode_server",
|
||||
"--onefile",
|
||||
"--clean",
|
||||
"--hidden-import=pystray",
|
||||
"--hidden-import=PIL",
|
||||
"--hidden-import=qrcode",
|
||||
"--hidden-import=aiohttp",
|
||||
"main.py",
|
||||
"--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)
|
||||
print("\n[✔] Compilazione completata con successo!")
|
||||
print(f"[✔] L'eseguibile si trova nella cartella: {os.path.abspath('dist')}")
|
||||
|
||||
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__":
|
||||
build()
|
||||
main()
|
||||
+25
-1
@@ -1,9 +1,32 @@
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
CONFIG_FILE = Path(__file__).parent / "config.json"
|
||||
|
||||
def _resolve_config_file() -> Path:
|
||||
"""Restituisce un percorso persistente e scrivibile per config.json (anche in binary PyInstaller)."""
|
||||
if getattr(sys, "frozen", False):
|
||||
exe_dir = Path(sys.executable).resolve().parent
|
||||
candidate = exe_dir / "config.json"
|
||||
if candidate.exists():
|
||||
if os.access(candidate, os.W_OK):
|
||||
return candidate
|
||||
elif os.access(exe_dir, os.W_OK):
|
||||
return candidate
|
||||
|
||||
# Fallback nella directory configurazione utente se la cartella dell'eseguibile è read-only
|
||||
if sys.platform == "win32":
|
||||
base_dir = Path(os.environ.get("APPDATA", Path.home())) / "BarcodeReaderServer"
|
||||
else:
|
||||
base_dir = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "barcode_reader_server"
|
||||
return base_dir / "config.json"
|
||||
|
||||
return Path(__file__).resolve().parent / "config.json"
|
||||
|
||||
|
||||
CONFIG_FILE = _resolve_config_file()
|
||||
|
||||
DEFAULT_CONFIG = {
|
||||
"host": "0.0.0.0",
|
||||
@@ -37,6 +60,7 @@ def load_config() -> dict:
|
||||
|
||||
def save_config(config: dict) -> None:
|
||||
try:
|
||||
CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(config, f, indent=4)
|
||||
except Exception as e:
|
||||
|
||||
@@ -20,6 +20,17 @@ from config import load_config
|
||||
from server_core import BarcodeServerCore
|
||||
|
||||
|
||||
def _configure_console_encoding() -> None:
|
||||
"""Evita UnicodeEncodeError su console Windows legacy (cp1252/cp850)."""
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
reconfigure = getattr(stream, "reconfigure", None)
|
||||
if callable(reconfigure):
|
||||
try:
|
||||
reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def print_ascii_qr(payload: str) -> None:
|
||||
"""Stampa un codice QR leggibile direttamente nel terminale."""
|
||||
import qrcode
|
||||
@@ -89,6 +100,7 @@ def run_gui_mode(server: BarcodeServerCore, start_minimized: bool):
|
||||
|
||||
|
||||
def main():
|
||||
_configure_console_encoding()
|
||||
parser = argparse.ArgumentParser(description="Barcode Reader PC Server - Catelli Srl")
|
||||
parser.add_argument(
|
||||
"--cli", "--headless", "--no-gui",
|
||||
|
||||
+87
-11
@@ -1,16 +1,92 @@
|
||||
@echo off
|
||||
setlocal EnableExtensions
|
||||
REM Script di avvio per Windows
|
||||
cd /d "%~dp0"
|
||||
|
||||
if not exist "venv" (
|
||||
echo [+] Creazione ambiente virtuale Python...
|
||||
python -m venv venv
|
||||
call venv\Scripts\activate.bat
|
||||
echo [+] Installazione dipendenze...
|
||||
pip install -r requirements.txt
|
||||
) else (
|
||||
call venv\Scripts\activate.bat
|
||||
chcp 65001 >nul 2>&1
|
||||
set "PYTHONUTF8=1"
|
||||
set "PYTHONIOENCODING=utf-8"
|
||||
|
||||
pushd "%~dp0" >nul 2>&1
|
||||
if errorlevel 1 (
|
||||
echo [!] Impossibile accedere alla directory dello script: %~dp0
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
python main.py %*
|
||||
pause
|
||||
set "PY_CMD="
|
||||
call :try_python py -3
|
||||
if not defined PY_CMD call :try_python python
|
||||
if not defined PY_CMD call :try_python python3
|
||||
|
||||
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.
|
||||
popd
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
set "VENV_DIR=venv"
|
||||
if exist "venv\bin" (
|
||||
if not exist "venv\Scripts\python.exe" (
|
||||
echo [!] Rilevato ambiente virtuale Unix/Linux in "venv". Uso "venv_win" per Windows.
|
||||
set "VENV_DIR=venv_win"
|
||||
)
|
||||
)
|
||||
|
||||
set "VENV_PY=%VENV_DIR%\Scripts\python.exe"
|
||||
if not exist "%VENV_PY%" (
|
||||
echo [+] Creazione ambiente virtuale Python in "%VENV_DIR%"...
|
||||
%PY_CMD% -m venv "%VENV_DIR%"
|
||||
if errorlevel 1 (
|
||||
echo [!] Errore durante la creazione dell'ambiente virtuale Python.
|
||||
popd
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
)
|
||||
|
||||
echo [+] Verifica dipendenze...
|
||||
"%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 ------------------------------------------------------------------
|
||||
)
|
||||
|
||||
"%VENV_PY%" main.py %*
|
||||
set "APP_EXIT=%ERRORLEVEL%"
|
||||
|
||||
popd
|
||||
if not "%APP_EXIT%"=="0" (
|
||||
echo.
|
||||
echo [!] Il server e' terminato con codice %APP_EXIT%.
|
||||
pause
|
||||
) else (
|
||||
pause
|
||||
)
|
||||
exit /b %APP_EXIT%
|
||||
|
||||
:try_python
|
||||
set "CANDIDATE=%~1"
|
||||
if not "%~2"=="" set "CANDIDATE=%~1 %~2"
|
||||
where %~1 >nul 2>&1
|
||||
if errorlevel 1 goto :eof
|
||||
%CANDIDATE% -c "import sys, venv; raise SystemExit(0 if sys.version_info >= (3, 9) else 1)" >nul 2>&1
|
||||
if not errorlevel 1 set "PY_CMD=%CANDIDATE%"
|
||||
goto :eof
|
||||
+11
-5
@@ -3,13 +3,19 @@
|
||||
set -e
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
if [ ! -d "venv" ]; then
|
||||
echo "[+] Creazione ambiente virtuale Python..."
|
||||
python3 -m venv venv
|
||||
VENV_DIR="venv"
|
||||
if [ -d "venv/Scripts" ] && [ ! -f "venv/bin/activate" ]; then
|
||||
echo '[!] Rilevato ambiente virtuale Windows in "venv". Uso "venv_unix" per Linux/macOS.'
|
||||
VENV_DIR="venv_unix"
|
||||
fi
|
||||
|
||||
source venv/bin/activate
|
||||
pip install -q -r requirements.txt
|
||||
if [ ! -f "$VENV_DIR/bin/activate" ]; then
|
||||
echo "[+] Creazione ambiente virtuale Python in $VENV_DIR..."
|
||||
python3 -m venv "$VENV_DIR"
|
||||
fi
|
||||
|
||||
source "$VENV_DIR/bin/activate"
|
||||
pip install --disable-pip-version-check -q -r requirements.txt
|
||||
|
||||
# Verifica presenza di Tkinter se non è richiesta la modalità CLI esplicita
|
||||
if [[ ! " $* " =~ " --cli " && ! " $* " =~ " --headless " && ! " $* " =~ " --no-gui " ]]; then
|
||||
|
||||
Reference in new issue
Block a user