standalone_mode.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import multiprocessing
  2. import os
  3. import signal
  4. import socket
  5. import tempfile
  6. import time
  7. from threading import Thread
  8. import webview
  9. shutdown = multiprocessing.Event()
  10. def open_window(event, fullscreen) -> None:
  11. window = webview.create_window('NiceGUI', url='http://localhost:8080', fullscreen=fullscreen)
  12. window.events.closing += event.set # signal that the program should be closed to the main process
  13. webview.start(storage_path=tempfile.mkdtemp())
  14. def check_shutdown() -> None:
  15. while True:
  16. if shutdown.is_set():
  17. os.kill(os.getpgid(os.getpid()), signal.SIGTERM)
  18. time.sleep(0.1)
  19. def activate(fullscreen: bool = False) -> None:
  20. multiprocessing.Process(target=open_window, args=(shutdown, fullscreen), daemon=False).start()
  21. Thread(target=check_shutdown, daemon=True).start()
  22. def find_open_port(start_port=8000, end_port=9000):
  23. for port in range(start_port, end_port+1):
  24. try:
  25. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  26. s.bind(('localhost', port))
  27. return port
  28. except OSError:
  29. pass
  30. raise OSError('No open port found')