launcher.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import os
  2. import subprocess
  3. import re
  4. import time
  5. import sys
  6. class Launcher(object):
  7. def __init__(self):
  8. pass
  9. @staticmethod
  10. def __terminal_output(message: str):
  11. print(f"[Launcher] {message}")
  12. def run(self):
  13. server_process = subprocess.Popen(["python", "./server/server.py"], stdout=subprocess.PIPE,
  14. stderr=subprocess.STDOUT, text=True, bufsize=1)
  15. server_ready = False
  16. port: int = 1024
  17. for line in iter(server_process.stdout.readline, ""):
  18. print(f"line: {line}")
  19. match = re.search(r"Server is running on port \[(\d+)\].", line.strip())
  20. if match is not None:
  21. port = int(match.group(1))
  22. break
  23. for line in iter(server_process.stdout.readline, ""):
  24. if "[Server] Server program is ready..." in line:
  25. server_ready = True
  26. break
  27. if not server_ready:
  28. print("Server failed to start. Exiting.")
  29. server_process.kill()
  30. return
  31. print("Server is ready, starting client...")
  32. client_env = os.environ.copy()
  33. client_env["PLC_SIM_PORT"] = f"{port}"
  34. client_process = subprocess.Popen(["powershell", "npm run dev"], env=client_env, cwd="./client")
  35. try:
  36. while True:
  37. return_code = client_process.poll()
  38. if return_code is not None:
  39. print("Client process terminated with return code", return_code)
  40. break
  41. time.sleep(0.5)
  42. server_process.terminate()
  43. server_process.wait()
  44. except KeyboardInterrupt:
  45. server_process.terminate()
  46. client_process.terminate()
  47. server_process.wait()
  48. except Exception as e:
  49. print(f"An error occurred: {str(e)}")
  50. server_process.terminate()
  51. client_process.terminate()
  52. server_process.wait()
  53. client_process.wait()
  54. sys.exit(1)
  55. # Usage:
  56. launcher = Launcher()
  57. launcher.run()