19
19
from .jupyter_client import JupyterClient
20
20
21
21
22
- def _get_free_port () -> int :
23
- with socket .socket (socket .AF_INET , socket .SOCK_STREAM ) as s :
24
- s .bind (("" , 0 ))
25
- return cast (int , s .getsockname ()[1 ])
26
-
27
-
28
22
class LocalJupyterServer (JupyterConnectable ):
29
23
class GenerateToken :
30
24
pass
@@ -69,9 +63,6 @@ def __init__(
69
63
)
70
64
71
65
self .ip = ip
72
- if port is None :
73
- port = _get_free_port ()
74
- self .port = port
75
66
76
67
if isinstance (token , LocalJupyterServer .GenerateToken ):
77
68
token = secrets .token_hex (32 )
@@ -98,8 +89,6 @@ def __init__(
98
89
"kernelgateway" ,
99
90
"--KernelGatewayApp.ip" ,
100
91
ip ,
101
- "--KernelGatewayApp.port" ,
102
- str (port ),
103
92
"--KernelGatewayApp.auth_token" ,
104
93
token ,
105
94
"--JupyterApp.answer_yes" ,
@@ -109,6 +98,9 @@ def __init__(
109
98
"--JupyterWebsocketPersonality.list_kernels" ,
110
99
"true" ,
111
100
]
101
+ if port is not None :
102
+ args .extend (["--KernelGatewayApp.port" , str (port )])
103
+ args .extend (["--KernelGatewayApp.port_retries" , "0" ])
112
104
self ._subprocess = subprocess .Popen (args , stdout = subprocess .PIPE , stderr = subprocess .PIPE , text = True )
113
105
114
106
# Satisfy mypy, we know this is not None because we passed PIPE
@@ -119,11 +111,22 @@ def __init__(
119
111
result = self ._subprocess .poll ()
120
112
if result is not None :
121
113
stderr += self ._subprocess .stderr .read ()
122
- print (f"token=[[[[{ token } ]]]]" )
123
114
raise ValueError (f"Jupyter gateway server failed to start with exit code: { result } . stderr:\n { stderr } " )
124
115
line = self ._subprocess .stderr .readline ()
125
116
stderr += line
117
+
118
+ if "ERROR:" in line :
119
+ error_info = line .split ("ERROR:" )[1 ]
120
+ raise ValueError (f"Jupyter gateway server failed to start. { error_info } " )
121
+
126
122
if "is available at" in line :
123
+ # We need to extract what port it settled on
124
+ # Example output:
125
+ # Jupyter Kernel Gateway 3.0.0 is available at http://127.0.0.1:8890
126
+ if port is None :
127
+ port = int (line .split (":" )[- 1 ])
128
+ self .port = port
129
+
127
130
break
128
131
129
132
# Poll the subprocess to check if it is still running
0 commit comments