File tree Expand file tree Collapse file tree 2 files changed +26
-6
lines changed Expand file tree Collapse file tree 2 files changed +26
-6
lines changed Original file line number Diff line number Diff line change @@ -114,7 +114,7 @@ if __name__ == "__main__":
114
114
# It is used only when directly running this script with Python,
115
115
# which will then initialize a localhost server.
116
116
117
- port = webviz_config .utils .get_available_port ()
117
+ port = webviz_config .utils .get_available_port (preferred_port = 5000 )
118
118
119
119
token = webviz_config .LocalhostToken (app .server , port ).one_time_token
120
120
webviz_config .utils .LocalhostOpenBrowser (port , token )
Original file line number Diff line number Diff line change 1
1
import os
2
2
import socket
3
+ from typing import Optional
3
4
4
5
5
- def get_available_port () -> int :
6
+ def get_available_port (preferred_port : Optional [ int ] = None ) -> int :
6
7
"""Finds an available port for use in webviz on localhost. If a reload process,
7
8
it will reuse the same port as found in the parent process by using an inherited
8
9
environment variable.
10
+
11
+ If preferred_port is given, ports in the range [preferred_port, preferred_port + 20)
12
+ will be tried first, before an OS provided random port is used as fallback.
9
13
"""
10
14
15
+ def is_available (port : int ) -> bool :
16
+ with socket .socket () as sock :
17
+ try :
18
+ sock .bind (("localhost" , port ))
19
+ return True
20
+ except OSError :
21
+ return False
22
+
11
23
if os .environ .get ("WEBVIZ_PORT" ) is None :
12
- sock = socket .socket ()
13
- sock .bind (("localhost" , 0 ))
14
- port = sock .getsockname ()[1 ]
15
- sock .close ()
24
+ port = None
25
+
26
+ if preferred_port is not None :
27
+ for port_to_test in range (preferred_port , preferred_port + 20 ):
28
+ if is_available (port_to_test ):
29
+ port = port_to_test
30
+ break
31
+
32
+ if port is None :
33
+ with socket .socket () as sock :
34
+ sock .bind (("localhost" , 0 ))
35
+ port = sock .getsockname ()[1 ]
16
36
17
37
os .environ ["WEBVIZ_PORT" ] = str (port )
18
38
return port
You can’t perform that action at this time.
0 commit comments