@@ -119,9 +119,12 @@ def _check_port(self) -> None:
119119 except requests .exceptions .ConnectionError :
120120 pass
121121 else :
122- if response .status_code == 200 :
123- self .port += 1
124- self ._check_port ()
122+ try :
123+ requests .post (f"http://localhost:{ self .port } /api/shutdown" )
124+ except requests .exceptions .ConnectionError :
125+ if response .status_code == 200 :
126+ self .port += 1
127+ self ._check_port ()
125128
126129 def _check_installed (self ) -> None :
127130 """if jupyter-kernel-gateway is installed"""
@@ -499,36 +502,41 @@ async def arestart(self) -> CodeBoxStatus:
499502 return CodeBoxStatus (status = "restarted" )
500503
501504 def stop (self ) -> CodeBoxStatus :
502- if self .ws is not None :
503- try :
504- self .ws .close ()
505- except ConnectionClosedError :
506- pass
507- self .ws = None
508-
509505 if self .jupyter is not None :
510506 self .jupyter .terminate ()
511507 self .jupyter .wait ()
512508 self .jupyter = None
513509 time .sleep (2 )
514510
515- return CodeBoxStatus (status = "stopped" )
516-
517- async def astop (self ) -> CodeBoxStatus :
518511 if self .ws is not None :
519512 try :
520- if not isinstance (self .ws , WebSocketClientProtocol ):
521- raise RuntimeError ("Mixing asyncio and sync code is not supported" )
522- await self .ws .close ()
513+ if isinstance (self .ws , ClientConnection ):
514+ self .ws .close ()
515+ else :
516+ loop = asyncio .new_event_loop ()
517+ loop .run_until_complete (self .ws .close ())
523518 except ConnectionClosedError :
524519 pass
525520 self .ws = None
526521
522+ return CodeBoxStatus (status = "stopped" )
523+
524+ async def astop (self ) -> CodeBoxStatus :
527525 if self .jupyter is not None :
528526 self .jupyter .terminate ()
529527 self .jupyter = None
530528 await asyncio .sleep (2 )
531529
530+ if self .ws is not None :
531+ try :
532+ if isinstance (self .ws , WebSocketClientProtocol ):
533+ await self .ws .close ()
534+ else :
535+ self .ws .close ()
536+ except ConnectionClosedError :
537+ pass
538+ self .ws = None
539+
532540 if self .session is not None :
533541 await self .session .close ()
534542 self .session = None
@@ -544,3 +552,6 @@ def kernel_url(self) -> str:
544552 def ws_url (self ) -> str :
545553 """Return the url of the websocket."""
546554 return f"ws://localhost:{ self .port } /api"
555+
556+ def __del__ (self ):
557+ self .stop ()
0 commit comments