2727import secrets
2828import time
2929import urllib .parse
30+ import requests
3031import typing
3132import scipy .spatial .transform
3233
@@ -241,12 +242,28 @@ def __init__(self,
241242 # A server is started in a subprocess, and we have to wait for it
242243 if self .SERVER_PORT is None :
243244 print ("Starting ZnDraw server, this may take a few seconds" )
244- self .port = port
245- self ._start_server ()
246- time .sleep (10 )
245+ Visualizer .SERVER_PORT = port
246+ self .server = subprocess .Popen (
247+ ["zndraw" , "--no-browser" , f"--port={ self .SERVER_PORT } " ],
248+ stdout = subprocess .DEVNULL ,
249+ stderr = subprocess .DEVNULL )
250+
251+ # Check that the server is up
252+ request_deadline = time .monotonic () + 30
253+ while time .monotonic () < request_deadline :
254+ try :
255+ r = requests .get (
256+ f"{ self .url } :{ self .SERVER_PORT } /health" , timeout = 1 )
257+ if r .status_code == 200 :
258+ break
259+ except requests .RequestException :
260+ pass
261+ time .sleep (0.5 )
262+ else :
263+ raise RuntimeError (
264+ "ZnDraw server did not start within the expected time" )
247265
248266 self ._start_zndraw ()
249- time .sleep (2 )
250267
251268 if vector_field is not None :
252269 self .arrow_config = {'colormap' : [[0.5 , 0.9 , 0.5 ], [0.0 , 0.9 , 0.5 ]],
@@ -265,16 +282,15 @@ def __init__(self,
265282 raise NotImplementedError (
266283 "Only Jupyter notebook is supported at the moment" )
267284
268- def _start_server (self ):
269- """
270- Start the ZnDraw server through a subprocess
271- """
272- Visualizer .SERVER_PORT = self .port
273-
274- self .server = subprocess .Popen (["zndraw" , "--no-browser" , f"--port={ self .port } " ],
275- stdout = subprocess .DEVNULL ,
276- stderr = subprocess .DEVNULL
277- )
285+ # Wait until the session is ready
286+ request_deadline = time .monotonic () + 30
287+ while time .monotonic () < request_deadline :
288+ if len (self .zndraw .sessions ) > 0 :
289+ break
290+ time .sleep (0.5 )
291+ else :
292+ raise RuntimeError (
293+ "ZnDraw session did not start within the expected time" )
278294
279295 def _start_zndraw (self ):
280296 """
0 commit comments