Mercurial > repos > shellac > guppy_basecaller
comparison env/lib/python3.7/site-packages/galaxy/util/sockets.py @ 0:26e78fe6e8c4 draft
"planemo upload commit c699937486c35866861690329de38ec1a5d9f783"
author | shellac |
---|---|
date | Sat, 02 May 2020 07:14:21 -0400 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:26e78fe6e8c4 |
---|---|
1 import random | |
2 import shlex | |
3 import socket | |
4 import subprocess | |
5 | |
6 | |
7 def unused_port(range=None): | |
8 if range: | |
9 return __unused_port_on_range(range) | |
10 else: | |
11 return __unused_port_rangeless() | |
12 | |
13 | |
14 def __unused_port_rangeless(): | |
15 # TODO: Allow ranges (though then need to guess and check)... | |
16 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
17 s.bind(('localhost', 0)) | |
18 addr, port = s.getsockname() | |
19 s.close() | |
20 return port | |
21 | |
22 | |
23 def __unused_port_on_range(range): | |
24 assert range[0] and range[1] | |
25 | |
26 # Find all ports that are already occupied | |
27 cmd_netstat = shlex.split("netstat tuln") | |
28 p1 = subprocess.Popen(cmd_netstat, stdout=subprocess.PIPE) | |
29 | |
30 occupied_ports = set() | |
31 for line in p1.stdout.read().split('\n'): | |
32 if line.startswith('tcp') or line.startswith('tcp6'): | |
33 col = line.split() | |
34 local_address = col[3] | |
35 local_port = local_address.split(':')[1] | |
36 occupied_ports.add(int(local_port)) | |
37 | |
38 # Generate random free port number. | |
39 while True: | |
40 port = random.randrange(range[0], range[1]) | |
41 if port not in occupied_ports: | |
42 break | |
43 return port |